Convert JSON data list string to object list in TypeScript

To convert a JSON data list string to a list of objects in TypeScript, you can use the parse() method of the JSON object.

For example, I have a list of classes returned from the backend as a GraphQL response as follows:

On the front-end, I define a class Clazz to store class information as follows:

To convert the above data response into a list of objects of the Clazz class, first, I will parse the above JSON data string into an object using the parse() method as follows:

From this object, we can call the node “clazzes” to get the class list as follows:

As you can see, I also assign the value of node “clazzes” to the list of Clazz objects. The result when I print to the console is as follows:

Here, I am defining the properties of the Clazz class as the same as the returned data, so the fields of the returned data are automatically assigned with the properties of the Clazz class. If the names of the properties of the Clazz class are different from the returned data, for example:

then even when printing all the class lists as above, the result is the same:

But if you just get the name of the class at the first element in the list:

You will see this name value is undefined as follows:

To solve this problem, you can use the parse() method with 2 parameters. The first parameter is a JSON string like I did above, the second parameter is a reviver function that is used to convert the keys and values of the JSON string before returning the result.

For my example, I will add a function to remove the key with the value “name” and add the key with the value “n” with the value of this key being taken from the value of the key “name” in the original JSON string as follows:

The keyword “this” here is the object that we have processed. We will add an “n” property to this object with the value taken from the “name” key of the corresponding original JSON string for that object.

The result will be as follows:

Add Comment