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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
const response: any = `{ "data": { "clazzes": [ { "id": "1", "name": "A1" }, { "id": "2", "name": "A2" }, { "id": "3", "name": "B1" }, { "id": "4", "name": "B2" } ] } }`; |
On the front-end, I define a class Clazz to store class information as follows:
1 2 3 4 |
export interface Clazz { id: string; name: string; } |
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:
1 |
let r = JSON.parse(response); |
From this object, we can call the node “clazzes” to get the class list as follows:
1 2 |
var clazzes: Clazz[] = r.data.clazzes; console.log(clazzes); |
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:
1 2 3 4 |
export interface Clazz { id: string; name: string; } |
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:
1 2 3 |
let r = JSON.parse(response); var clazzes: Clazz[] = r.data.clazzes; console.log(clazzes[0].n); |
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:
1 2 3 4 5 6 7 |
let r = JSON.parse(response, function (key, value) { if (key === "name") { this.n = value; return; } return value; }); |
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: