2

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

asked Oct 3, 2017 at 10:56
1
  • 1
    profile.results it's an array not an object, you have to use something like profile.results[index].po_number, profile.results[0].po_number for example. Commented Oct 3, 2017 at 10:57

3 Answers 3

6

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);

answered Oct 3, 2017 at 10:58
Sign up to request clarification or add additional context in comments.

Comments

0

results is an array.

To access po_number, you'll need to do something like:

console.log("profile: "+ profile.results[0].po_number)

Make sure you dynamically iterate the array to access that value.

Example (in underscore/lodash) :

_.each(profile.results, (result) => { 
 console.log("profile: " + result.po_number);
});
answered Oct 3, 2017 at 11:04

Comments

0
var profile = JSON.parse(JSON.stringify(data[0]))
console.log("profile: "+ profile.po_number)
Phani Kumar M
4,5781 gold badge16 silver badges26 bronze badges
answered Oct 3, 2017 at 11:01

1 Comment

Why would you stringify the data then parse it?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.