Transform Dictionary JSON into Typescript model

How can I convert the provided JSON structure into a TypeScript interface to ensure type safety?

{
  "attributes1": {
    "myKey1": {
      "myinnerKey11": {
        "value": "value 1",
        "name": "name 1"
      },
      "myinnerKey12": {
        "value": "value 1",
        "name": "name 1",
        "otherKey": "key 2"
      }
    }
  },
  "attributes2": {
    "myKey2": {
      "myinnerKey21": {
        "value": "value 1",
        "name": "name 1"
      },
      "myinnerKey22": {
        "value": "value 1",
        "name": "name 1",
        "otherKey": "key 2"
      }
    }
  }
}

My attempt at creating the corresponding interface is as follows:

export interface IFinalObj {
    attributes1: IAttributes1;
    attributes2: IAttributes2;
}

interface IMyInnerObj {
    value: string;
    name: string;
    otherKey?: string;
}

interface IDynamicInnerKey {
    [a: string]: IMyInnerObj
}
    
interface IAttributes1 {
    myKey1: IDynamicInnerKey;
}

interface IAttributes2 {
    myKey2: IDynamicInnerKey;
}

I'm unsure about how to handle changes in key values and additions of new objects dynamically.

Answer №1

If you're in need of the Record interface or want to generate typings from data, then check out http://json2ts.com/. It's a great tool for that purpose.

I created a basic version and tested it with your model:

interface ITest {
  attributes1: {
    myKey1: {
      myinnerKey11: {
        value: string,
        name: string
      },
      myinnerKey12: {
        value: string,
        name: string,
        otherKey: string
      }
    }
  },
  attributes2: {
    myKey2: {
      myinnerKey21: {
        value: string,
        name: string
      },
      myinnerKey22: {
        value: string,
        name: string,
        otherKey: string
      }
    }
  }
}

You can test it out here: https://json2dts.stackblitz.io/ and view the source code at: https://stackblitz.com/edit/json2dts

Keep in mind, this version is quite simple and doesn't include any pattern matching.

Answer №2

interface iData {
  "attributes3": {
    "myKey3": {
      "myinnerKey31": {
        value: string,
        title: string,
        extraKey?: string
      },
      "myinnerKey32": {
        value: string,
        title: string,
        extraKey?: string
      }
    }
  },
  "attributes4": {
    "myKey4": {
      "myinnerKey41": {
        value: string,
        title: string,
        extraKey?: string
      },
      "myinnerKey42": {
        value: string,
        title: string,
        extraKey?: string
      }
    }
  }
}

const newData: iData = {
  "attributes3": {
    "myKey3": {
      "myinnerKey31": {
        "value": "data value",
        "title": "element title"
      },
      "myinnerKey32": {
        "value": "data value 2",
        "title": "element title 2",
        "extraKey": "another key"
      }
    }
  },
  "attributes4": {
    "myKey4": {
      "myinnerKey41": {
        "value": "new value",
        "title": "latest title"
      },
      "myinnerKey42": {
        "value": "other value",
        "title": "random title",
        "extraKey": "unique key"
      }
    }
  }
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS efficiently preloading json file

I am just starting to learn about angularJS. Apologies if my question is not very clear. Here is the problem I am facing: I have a JSON file that is around 20KB in size. When I attempt to load this file using the 'factory' method, I am receivin ...

"Disabling a FormControl within a FormArray in Angular 4: A Step-by-

I've come up with a code snippet below that I thought would disable the FormControl in a FormArray. some.component.html <form [formGroup]="testForm"> <div *ngFor="let num of countArr"> <input type="text" formNameArray="arr ...

Unable to subscribe to mergeMap observable in Angular 13

I am currently working on implementing a connection scenario in Angular that is based on user roles. When the user clicks on the "CONNEXION" button after filling out the form with their username and password, two API URLs are triggered to facilitate the sa ...

Navigating on Angular 2 without refreshing the page

Seeking advice for my Angular 2 single-page application project which heavily uses maps. The main requirement is that when a point on the map is clicked, the URL should update so that upon refresh, the map zooms into that specific point (and also to allow ...

Communicating Data Between Controllers in Node.js

Within my PlantsController, I extract the Plants using the following method: function getAll() { const plants= HttpRequestPromise.get(config.ApiURL+'allPlants', config.head); return plants; } export class PlantsController { ... public ...

Execute the form validation and submission simultaneously

I am facing an issue with my form validation and submission process. When I click on the creer button, the form validation works fine but the submit function does not work. I don't see any errors in my console. I have tried using the onsubmit() method ...

No TypeScript error in Angular app when assigning a string to a number data type

Today, I encountered some confusion when my app started acting strangely. It turns out that I mistakenly assigned a string to a number without receiving any error alerts. Any thoughts on why this happened? id:number; Later on: this.id = ActiveRoute.params ...

Oops! There seems to be an issue with Angular - I'm getting an

I need to retrieve JSON data from the server and only display it on the web page after clicking a button. However, I encounter an error after the first click: core.js:4352 ERROR TypeError: Cannot read property 'imie' of undefined at HttpTestC ...

I aim to display interconnected information from various APIs in a cohesive manner

I am working with two APIs: component.ts ngOnInit(): void { this.getQueryCountriesList().subscribe(arg => { this.countryDatas = arg; }); this.getQueryNights().subscribe(obj => { this.nightDatas = obj; }); ...

Leverage C# model classes within your Angular application

Just wanted to express my gratitude in advance import { Component, Inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-fetch-data', templateUrl: './fetch-data. ...

angular2 angular-entity directive

I have developed a component that accepts a template: export class TemplateParamComponent implements OnInit { @Input() items: Array<any>; @Input() template: TemplateRef<any>; } Here is the HTML code: <template #defaultTemplate le ...

Tips for dynamically adding an object to the formArrayName in Angular reactive forms

Currently, I am facing an issue with loading my array of objects response into a multiselect using ng-select. The structure of my response data looks like this: The formModel setup in my code is as follows: clientForm = this.fb.group({ custom : this. ...

Discovering the best method to retrieve user details (email address) following a successful login across all pages or components within Angular

Discovering the world of Angular and TypeScript is quite exciting. In my Angular project, I have 8 pages that include a login and registration page. I'm facing an issue where I need to access the user's email data on every page/component but the ...

Why is it that servlets are unable to send custom JSON strings, and why is it that Ajax is unable to receive them?

I have developed a servlet that responds with a simple JSON list: public void addCategory(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { logger.log(Level.INFO, "Adding the category"); ObjectifyS ...

incomplete constructor for a generic class

I have multiple classes that I would like to initialize using the following syntax: class A { b: number = 1 constructor(initializer?: Partial<A>) { Object.assign(this, initializer) } } new A({b: 2}) It seems to me that this ini ...

"Utilize Typescript for defining the parameter type in this

defineProperties(Element.prototype, { querySelector: { value: querySelectorPatched, writable: true, enumerable: true, configurable: true, }, querySelectorAll: { value(this: HTMLBodyElement): NodeListOf< ...

JSON isn't transmitting any information

Having an issue with Json that's puzzling me. I'm using ajax to call a Controller method that takes a string as input and returns a List of my defined class. The json call is triggered by a dropdown menu change, loading the corresponding fields ...

What is the best way to organize class usage within other classes to prevent circular dependencies?

The engine class presented below utilizes two renderer classes that extend a base renderer class: import {RendererOne} from "./renderer-one"; import {RendererTwo} from "./renderer-two"; export class Engine { coordinates: number; randomProperty: ...

Error encountered with the root reducer due to data type mismatch

Within my Redux store setup, I have a persistedReducer initialized to include the redux-persist config and the "rootReducer": client/src/redux/store.ts: import { configureStore } from '@reduxjs/toolkit'; import { persistStore, persistReducer } f ...

Trouble with fetching data from Swift/Firebase in the exact order it was entered?

Encountering issues with fetching data from Firebase in the exact order it was entered. I've experimented with different methods, including .valueAdded and .value, but haven't been successful in maintaining the original order. Could it be that my ...