user1125829 user1125829 - 8 months ago 101
Javascript Question

how to parse json array in node js

I was trying below code,where body is response from HTTP GET. When I tried to run it, I am getting below error.


Cannot read property 'po_number' of undefined


{
"d": {
"results": [
{
"po_number": "PO1001",
"product_id": "PD1001",
"message": "Exists",
"timestamp": "2016-05-01"
}
]
}
}


How to access po_number

var profile = JSON.parse(body);
console.log("profile: "+ profile.results.po_number)


I am getting undefined when i access above code

Answer Source

You missed one step. You missed the object d and that the results is an array. So first access the 0 indexed item.

You need to get via profile.d.results[0].po_number.

const jsonObj = `{ "d": {
     "results": [
      {
          "po_number": "PO1001",
          "product_id": "PD1001",
          "message": "Exists",
          "timestamp": "2016-05-01" 
      }]
}}`;

var profile = JSON.parse(jsonObj);
console.log(profile.d.results[0].po_number);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download