What is the simplest method for generating a TypeScript object using JSON data as the input?

When working with Angular2 (TypeScript), I encountered a class that has the following constructor:

 export class DataModel {
    constructor(public date_of_visit: string,
                public gender: boolean,
                public year_of_birth: number,
                public height: number,
                public weight: number){}
 }

In addition, there is a JSON object available:

json = {"date_of_visit": "23/09/2016", "gender": 1, "year_of_birth": 1975, "height":185, "weight": 85}

My question: How can we easily create an instance of DataModel using the JSON data as input? Can we achieve this with something like new DataModel(**json)?

Answer №1

When it comes to compile time casting, you can achieve it like this:

let userData = {"username": "JohnDoe", "email": "johndoe@example.com", "age": 30, "isAdmin": false} as UserData;

Answer №2

Utilizing casting will help you accomplish:

let instance: DataModel = {"date_of_visit": "23/09/2016", "gender": 1, "year_of_birth": 1975, "height":185, "weight": 85} as DataModel;

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

How can a default value be assigned to an ag-Grid filter?

Is there a way to set a default value in ag-grid filter text that is displayed to the user but not applied to the actual results? this.columnDefs = [ { headerName: this.pageData["tbm.line.list.grid.phonenumber"], field: 'tn', /*sor ...

TS2339: The attribute 'size' is not present on the 'string' data type

Within my Typescript file, I have the following line: return stringToValidate.length <= maxLength; Despite the code executing without issues, an error is displayed: TS2339: Property 'length' does not exist on type 'string'. I am cu ...

Please submit your message in Slack with just plain text and no JSON format

I attempted to send a JSON to create a poll for a Slack bot. According to the documentation here, I need to use certain methods and buttons should be used as attachments. Here is an example URI: https://slack.com/api/chat.postMessage?token=some token& ...

Guide on inserting tooltip to designated header column in primeNG data table

Html <p-table #dt1 [columns]="cols" [value]="cars1"> <ng-template pTemplate="header" let-columns> <tr> <th *ngFor="let col of columns"> {{col.header}} </th> ...

Creating personalized directives

Seeking help on Vue's custom directives with Typescript integration. Despite extensive search online and in chat rooms, I am unable to find any solutions. <button v-clickOutside="myFunc"> Click Outside </button> Implementing the ...

What is the best way to convert an array into an object by leveraging the power of the reduce

I want to use the .reduce function to transform the array into an object with the following structure: { "date": xxxx, "amount": xxxx, } Instead of: {01-2018: 0, 09-2019: 0, 02-2020: 0, 03-2020: 142.95999999999998, 04-2020: 652.78, ...} I aim to achiev ...

What is the best way to transform a string resembling JSON or a JS object into a valid JS object?

The specific String in question was originally part of a JavaScript object as shown below: var nameVal = "Jacob"; var favNumbersVal = "{\"firstNum\":0, \"secondNum\":1, \"thirdNum\":2}"; var aJSObject = { "name" = nameV ...

Calculate the distance between two markers using agm-direction

Despite trying everything, I have been unable to calculate the distance between two points using the path we take, not the direct distance. I have attempted to use the travelMode but have had no success. Any assistance on this matter would be greatly appre ...

Verify the syntax and format of the POST body request using Node.js Express

Is there a way to verify the syntax of the POST request body received by my server on the '/route' route? I need to ensure: The body is in JSON format, The syntax is correct (no missing brackets or quotes). /// My Code /// app.use(express.jso ...

iOS 7 is experiencing crashes due to an unrecognized selector being sent to an instance with [NSNull intValue]

Having an issue with retrieving data from a JSON service. For some reason, the code works fine on iOS 5, 5.1, 6.0, and 6.1 but crashes on iOS 7 when trying to access a specific JSON value: { voteAverageRating = 0; voteCount = 0; } This is the ori ...

Testing a private method in an Angular 2 component by injecting a service

I have a confidential function where I am invoking a method defined in a service to retrieve some information. This service is implemented as a class. Here is a snippet of code in Angular2: private _data: DataService; private _result: any; private _get ...

Exploring Gson's method for deserializing JSON containing optional fields

I'm currently utilizing Gson for deserializing a JSON string obtained from an API using the code snippet below. Gson gson = new Gson(); Map<String, CustomDto> test = gson.fromJson(result, new TypeToken<Map<String, CustomDto>>() {}.g ...

Developing a functionality to search for specific values within JSON properties

Hello, I have a question about implementing a partial search on a specific property within JSON data. Basically, what I'm trying to achieve is that if I type in "Jac" into the input field, it will search the JSON data for similar strings like Jacob, J ...

React, Storybook - Error TS2307: Button module not found or its type declarations. Can Storybook resolve this issue?

In my React project, I have a Button component created with "create-react-app" that uses absolute paths for importing. When trying to import { Button, ButtonProps } from 'Button', I encountered an error with TS2307. The absolute path 'Butto ...

Guide to Making a Basic TypeScript Metadata Tag in Your Code

I'm looking for a way to format certain fields before sending them to the server-side. My goal is to serialize specific fields of my TypeScript classes using custom serializers. An example of what I'm aiming for is as follows: export class Pers ...

The result is being presented enclosed in quotation marks within the JSON format

When I attempt to retrieve a JSON string via jQuery using the function below, I encounter an issue where my JSON result is wrapped in double quotes. I came across a post on Stack Overflow, suggesting that I should rely on the JSON serialization of the fram ...

Converting Strings into Key-Value Pairs or JSON Format Using Dart

My String contains key-value pairs enclosed in curly braces {} and separated by commas , While I am aware of using json.decode or jsonDecode, the issue lies in the fact that neither the key nor the value is wrapped in quotes "". Thus, json.decod ...

Ways to effectively leverage the types from lib.d.ts?

It appears that the issue at hand is related to WebStorm IDE. I have reported it to WebStorm and you can track the progress here. Currently, I am working with Angular 2 and TypeScript 2. I am wondering how to explicitly utilize the location from lib.d.ts ...

Contrasting Sequential and Parallel Execution in Quantum Computing

During the execution of an asynchronous operation, is it handled as a Sequential call or Parallel call at runtime? Can you explain how the $q handles this? Please provide a brief explanation of the differences between Sequential and Parallel e ...

What is the process for setting up a function to generate a POST request in a Spring Boot application?

In my current Springboot project, I am utilizing the Postman client to send a post request with a JSON body. The following image is relevant to this process. image POST http://localhost:8080/api/v1/orders Json Body= { "fuelType": "Pe ...