12

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.

1 Answer 1

21

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());
Sign up to request clarification or add additional context in comments.

12 Comments

One additional remark to the already good answer: There is no guarantee that the JSON.parsed data realy conforms to the interface that was defined after parsing. If the server suddenly sends other data it might no longer conform to it, and accessing the data through the previously expected interface might lead to a crash. So it's always recommended to validate the data between parsing and using it.
It is indeed an excellent answer, however, were i to insert into the HTML, please how would go about. I used *ngFor = "let obj of foundData" but cannot seem to get the list of name
Oh and @Matthias247, how do i validate the data please?
@JendorskiLabs <p *ngFor = "let item of obj.string">{{ item.name }}</p>
Thanks, i tried that already. error from JavaScript Console reads Cannot read property 'string' of undefined. I also tried <p *ngFor = "let item of obj">{{ item.string[0].name }}</p> to no avail.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.