Transform a dynamic JSON configuration into a Typescript class

After extensively searching the web, reading through typescript documents, and reviewing numerous responses here on stack overflow, I have yet to find a solution that fully addresses my query:

In my typescript code, I import a JSON file with the following structure:

[
    {
        "property" : "FristName",
        "type" : "string"
    },
    {
        "property" : "LastName",
        "type" : "string"
    },
    {
        "property" : "Age",
        "type" : "number"
    }
]

The key property represents a class property while the key type indicates the property type.

My goal is to create a class constructor in such a way that it dynamically generates the following at runtime:

class Person {
    public FirstName: string;
    public LastName: string;
    public Age: number
{

The JSON array may contain multiple object literals indexed from n. These object literals are static in structure and will always consist of the two attributes attribute and type.

Answer №1

One recommended approach is to implement a PersonCreator class that includes a public method named createFromJSON. This method should take a JSON string as input and produce an instance of the Person class.

import { Person } from "person";

export interface PersonAttributes {
  [index: number]: {attribute: string, type: "string" | string };
}

export class PersonCreator {
    createFromJSON(attributes: PersonAttributes): Person {
        return new Person(attributes[0].attribute, attributes[1].attribute);
    }
}

To utilize the factory, follow these steps:

import { PersonCreator, PersonAttributes } from "creators";

const data: PersonAttributes = require("person_attributes.json");

const createdPerson: Person = (new PersonCreator()).createFromJSON(data);

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

Eliminate the need to input the complete URL every time when making server calls

Currently, my springbok application has a React-Typescript frontend that is functioning well. I am using the request-promise library to make requests like this: get('http://localhost:8080/api/items/allItems', {json: true}). However, I would like ...

Difficulty Determining Literal Types that Expand a Union of Basic Data Types

Below are the components and function I am working with: interface ILabel<T> { readonly label: string; readonly key: T } interface IProps<T> { readonly labels: Array<ILabel<T>>; readonly defaultValue: T; readonly onChange ...

What is the best way to access automatically generated JavaScript variables in TypeScript?

I am currently facing an issue with integrating a Google login API in my React project and I need some help. The problem arises when the user already has an active session, rendering the API unnecessary. The Javascript solution provided is as follows: co ...

The object fails to initialize using data retrieved from the JSONP API

As a newcomer to the world of jQuery and Javascript, I am currently working on creating an object that will store information obtained from an API. The objective is to have this object hold basic info for each user in the users array. My approach involves ...

Obtain PHP array after making an AJAX request

I'm using $.post() to send a JavaScript object and I need to receive an array in return. JavaScript Code var ajaxData = {action:"createuser"} $("input[required]").each(function(){ var attr = $(this).attr("name"); ajaxData[attr] = $(this).val ...

The 'doRequest' property is not found on the type 'any[]'

Attempting to develop a custom hook in TypeScript for managing errors & API requests, but encountering a type error where a property does not exist on type 'any[]' Here is the code for the hook: import axios from 'axios'; import { ...

Transforming Excel data into JSON format using ReactJS

Currently, I am in the process of converting an imported Excel file to JSON within ReactJS. While attempting to achieve this task, I have encountered some challenges using the npm XLSX package to convert the Excel data into the required JSON format. Any as ...

Tips for updating the value of a JSON by accessing the specific path in Java

I am trying to change the value of "$.widget.debug" in my code. I have experimented with numerous libraries, but haven't been successful in achieving this task. { "widget": { "debug": "on", "window": { "title": "Sample ...

Changing the value of a JSON object

My goal is to update a value in a JSON file by removing the last character from a URL. I wrote the following code, but unfortunately, it doesn't seem to be making any changes. I'm a bit lost on what went wrong... def modify_json(file): with ...

The element event does not trigger an update on the view

I am trying to display the caret position of my editor on a specific place on the website. I have created a directive and service to share variables between the controller and directive. Inside the directive, I have enabled events like "keyup", "mouseup", ...

Is it possible for Typescript and Next.js to import a different project's *source code* only from the module's root directory?

Issue with Sharing React Components between Closed and Open Source Next.js Projects I am facing a challenge in my development setup involving two Next.js projects, one closed source (Project A) and the other open source (Project B). In Project A, which is ...

Displaying a segment of information extracted from a JSON array

I'm currently tackling a project that involves using React, Redux, and TypeScript. Within the JSON file, there is a key-value pair: "data_start": "2022-09-02" Is there a way to display this date in a different format, specifical ...

Generating and setting an object property in TypeScript at runtime

In my code, I have defined an interface as follows: export interface OurHistory { ourHistory?: object; step1?:object; step2?:object; } Within the HistoryComponent class, I am doing the following: export class HistoryComponent implements OnInit, On ...

Sending a request to a JSON file using Ajax

I have 2 questions: 1. I am trying to run this file, but it is not giving any errors or showing results. Please help me identify the problem. 2. I added a dropdown menu in my HTML file, but I'm unsure how to use it to display a list of names. Any sugg ...

Exploring the extraction of dual values from a deeply nested JSON string using Jackson

I'm currently using the Jackson library for deserializing JSON data. Specifically, I am trying to extract only two values from this JSON - c1 and d1. Here is a snippet of the code I have used so far... How can I retrieve the correct approach to access ...

What impact does nesting components have on performance and rendering capabilities?

Although this question may appear simple on the surface, it delves into a deeper understanding of the fundamentals of react. This scenario arose during a project discussion with some coworkers: Let's consider a straightforward situation (as illustrat ...

Learn how to dynamically alter the background color of a webpage by utilizing a JSON API for random color selection

My goal is to trigger a javascript function onload that will dynamically change the background color of the webpage using random colors fetched from a JSON file. ...

What is the best way to store JSON data in Mongoose database?

I have some json data that I need to store in a mongoose database, but I'm struggling with how to structure my mongoose schema. data: { 'posts[0][commentId]': '0', 'posts[0][id]': '1', 'posts[0][post ...

Obtaining the value of an ion-toggle in Ionic2 using the ionChange

Below is the toggle I am referring to: <ion-toggle (ionChange)="notify(value)"></ion-toggle> I am looking for a way to retrieve the value of the toggle when it is clicked in order to pass it as a parameter to the notify method. Any suggestion ...

Utilizing jQuery to Consume WCF Services in JSON Format

When utilizing a contract: namespace ACME.FooServices { [ServiceContract] public interface IFooService { [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, ...