Parse a JSON array in Typescript

I have a JSON response from a remote server this way:

{
  "string": [
    {
      "id": 223,
      "name": "String",
      "sug": "string",
      "description": "string",
      "jId": 530,
      "pcs": [{
        "id": 24723,
        "name": "String",
        "sug": "string"
      }]
    }, {
      "id": 247944,
      "name": "String",
      "sug": "string",
      "description": "string",
      "jlId": 531,
      "pcs": [{
        "id": 24744,
        "name": "String",
        "sug": "string"
      }]
    }
  ]
}

To parse the answer, to indicate "name" and "description", I wrote this code:

interface MyObj {
  name: string
  desc: string
}
let obj: MyObj = JSON.parse(data.toString());

My question is how to get the name and description into a list that can be displayed.

+4
source share
1 answer

You have specified the wrong type for your parsed data. There should be something like this:

interface MyObj {
  name: string
  description: string
}

let obj: { string: MyObj[] } = JSON.parse(data.toString());

So this is not MyObj, the object object with the property stringcontains an array MyObj. How can you access this data as follows:

console.log(obj.string[0].name, obj.string[0].description);

Instead of using an anonymous type, you can also define interfacefor it:

interface MyRootObj {
  string: MyObj[];
}

let obj: MyRootObj = JSON.parse(data.toString());
+9

Source: https://habr.com/ru/post/1665406/


All Articles