Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON array in Typescript

i have a JSON response from remote server in 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"
      }]
    }
  ]
}

In order to parse the response, to list out the "name" & "description", i have written this code out:

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

My question is how do i obtain the name and description into a list that can be displayed.

like image 222
Jendorski Labs Avatar asked Dec 31 '16 12:12

Jendorski Labs


1 Answers

You gave incorrect type to your parsed data. Should be something like this:

interface MyObj {
  name: string
  description: string
}

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

So it's not MyObj, it's object with property string containing array of MyObj. Than you can access this data like this:

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

Instead of using anonymous type, you can also define interface for it:

interface MyRootObj {
  string: MyObj[];
}

let obj: MyRootObj = JSON.parse(data.toString());
like image 164
Yaroslav Admin Avatar answered Oct 21 '22 20:10

Yaroslav Admin