Utilize class-transformer to convert JSON data into a class instance

Is there a way to create an instance of the Customer class from a Json object without facing type safety issues?

I attempted to use the plainToInstance function from class-transformer but encountered difficulties obtaining the correct class instance in Typescript.

What am I doing wrong?

Import

import { plainToInstance } from 'class-transformer';

Customer JSON

    const json = `{
      "id": "1",
      "name": "Jogn",
      "surname": "Doe",
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80eaaee4efe5aef4e5f3f4c0e7ede1e9ecaee3efed">[email protected]</a>",
      "phone": "123456789"
  }
}
`;

Customer class definition

import { Field, ObjectType, Directive, ID } from '@nestjs/graphql';
import { Address } from './address';

@ObjectType()
@Directive('@key(fields: "id")')
export class Customer {

  @Field(() => ID)
  id: string;

  @Field()
  name: String;

  @Field({nullable: true})
  surname?: String;

  @Field()
  email: String;

  @Field({nullable: true})
  phone?: String;

  @Field()
  customerType: String;

  @Field()
  customerStatus: String;

  @Field(() => [Address], { nullable: true })
  addresses?: [Address]
}

Transformation from Json to Customer instance

let customer : Customer = plainToInstance(Customer, json) as Customer;
console.log('customer.email);

Console result

Customer email: undefined

Unfortunately, I couldn't retrieve the email of the customer using this method

This is what happens when I log the entire customer variable

console.log(customer);

{
      "id": "1",       
      "name": "Jogn",  
      "surname": "Doe",
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d0bafeb4bfb5fea4b5a3a490b7bdb1b9bcfeb3bfbd">[email protected]</a>",
      "phone": "123456789"
}

Test with creating the Customer instance inline

var x = new Customer();
x.id = "123";
console.log(x)

After trying this approach, the object looks proper in the console

Customer { id: '123' }

Answer №1

Make sure to provide a JSON object to the function plainToInstance, not just a string.
For example, your json variable should look like this:

const json = {
  id: '1',
  name: 'John',
  surname: 'Doe',
  email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0963276d666c277d6c7a7d496e64686065276a666">',
  phone: '123456789',
};

Check out this live example on Stackblitz

Answer №2

In order to utilize the plainToInstance method properly, it is essential that the second attribute be a plain object. Therefore, you must first parse your JSON string into an object like so:

const customer = plainToInstance(Customer, JSON.parse(json))

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

Sending two variables as JSON in Django using HTML can be achieved by creating a JSON object in the JavaScript

I need to display two different HTML samples and return them as a response to an AJAX request. Here is a snippet of my code in the view: def getClasses(request): User = request.user aircomcode = request.POST.get('aircompany_choice', Fals ...

No tables were obtained when scraping tables in R despite having two tables on the webpage

My current project involves extracting NBA lineup data from The main aim is to retrieve the entire table, consisting of 2000 rows. However, I am facing difficulty in locating the data within the HTML nodes. I have attempted various methods so far: One ap ...

Querying multiple models and organizing their properties in the JSON body

I have encountered an issue with structuring the JSON response body of my API call function that generates a summary of students based on their attendance status. It seems like the current structure is not aligning with what I intend to display due to the ...

Ways to observe redux action flow within a component

I am currently developing a React application structured with the following elements: redux typesafe-actions redux-observable My query is: How can I trigger a UI action when a specific redux action occurs? For instance, if we have these asynchronous ac ...

Handling events in React using TypeScript

Currently diving into the world of React with Typescript and encountered a challenge involving event handling using the onClick property. I have a react component displaying a list of items from an array, and I aim to log the clicked item in the console. I ...

Is it possible for an ASP.NET web service to unexpectedly terminate due to the presence of "&" in

I have a mobile application for iPhones that communicates with an asp.net webservice using JSON. Everything works smoothly with all the data, but whenever I include an "&" symbol in any data field, it triggers a server error as shown below System.Argumen ...

What causes the difference in behavior of my PowerShell code when it is invoked as a module from another file?

Recently, I developed a PowerShell function that automates the merging of .json files. The process is quite straightforward: The function takes in three paths: one for the old file, one for the new file, and the third for the target. It navigates through ...

Concerns with combining key value pairs in Typescript Enums

Could you help me figure out how to properly implement an enum in my drop-down so that I can only display one value at a time? Currently, I am seeing both the key and the value in the list. This is my enum: export enum VMRole { "Kubemaster" = 0, "Kub ...

Set an enumerated data type as the key's value in an object structure

Here is an example of my custom Enum: export enum MyCustomEnum { Item1 = 'Item 1', Item2 = 'Item 2', Item3 = 'Item 3', Item4 = 'Item 4', Item5 = 'Item 5', } I am trying to define a type for the f ...

Avoiding duplication of jquery when using webpack and typescript

I encountered an error message that reads: Uncaught TypeError: $(...).dialog is not a function The issue appears to be arising from importing jquery twice, and I am struggling to find a solution. Additionally, the error references bootstrap in the follo ...

Is there a variety of values for the POST value field?

Currently, I am working on a contact edit form. The entire form loads dynamically via ajax, appearing in a lightbox. The form is pre-populated with the existing contact's data. After clicking the edit button, jQuery scans for any changes in the for ...

What is the best method for adding a new key and value to a JSON array in MongoDB?

Is there a way to append a new key and value in a JSON array? I attempted to use the push keyword in an update query, but the result was unexpected. Here is what I tried: db.users.updateOne({"name":"viki"},{$push{"address.district":"thambaram"}}) This ...

How can we import the entire Jasmine library using CucumberJS?

I am currently trying to implement unit testing using Jasmine and CucumberJS in my Angular v9 application. I have followed the tutorial provided by cucumber.io to set up cucumber as the default runner. However, I am facing difficulties in using Jasmine met ...

Retrieve a data value from a JSON object by checking if the ID exists within a nested object

I am facing the challenge of navigating through a JSON object where child objects contain IDs that need to be matched with parent properties. The JSON structure looks like this: { id: 1, map: "test", parameter_definitions: [{ID: 1, pa ...

jqGrid - What is the best way to set up jsonreader in conjunction with Jayrock?

Seeking insights from anyone familiar with this topic. The JSON string that works well with jqGrid looks like this: {'page':'1','total':1,'records':'4','rows':[{'id':1,'title' ...

Identifying two separate lines within a document scan

I am trying to open and read a specific file with this code snippet: f = subprocess.Popen(["../../../abc/def/run_script.sh", "cat", "def/data/ex/details.json"], stdout=subprocess.PIPE) out = f.stdout.readline() The content of the file I'm reading is ...

Secure JSONP endpoint with additional layers of protection

I am working on a project that involves utilizing an endpoint that delivers JSON data through AJAX on a website. Now, I am interested in accessing the same endpoint from various other sites (each on different domains), so I am considering transforming it ...

Flask response fails to retain non-visible characters in string

My Python string variable has a unique format: '\x1d0103671286378126378127812\x1d1232321102I009B\x1d71012321271' When I send it in a json response, the \x1d characters disappear. Strangely enough, when I print it on the con ...

What is the best way to divide my discord.py balance among multiple servers?

I have implemented an economy system in my discord.py bot where users can earn coins. However, the issue is that everyone's balance (coin amount) is connected across all servers. Below is the code snippet responsible for managing the .json file: async ...

Leveraging File functionality in TypeScript

In the process of developing a web application with Angular 4 and Typescript, I encountered an issue while attempting to retrieve the date of a file for upload. Specifically, when trying to access the lastModified property of a File object, Typescript retu ...