0

i've been looking for this for quite some time and couldn't really find anything. Most guides/doc assumes i am using same app but this is not a case. So i have made node.js api with test call GET api.raidcore.xyz/items which returns an array as you'd expected: Javascript {"data":[{"_id":"5834551dfa44228b52645f43","itemDesc":"lorem ipsum dolor sit amet","itemName":"test item","__v":0}]} Now what i want to do is display jst itemName to make list or whatever.

res.on('data', function(data){
 var json = json.parse(data);
 let name = json.itemName;
 console.log(name);
}

returns undefined object. if i log data alone, it displays everything ok. So how do i actually select what i want to show?

4
  • 3
    JSON.parse(, should be uppercase the json part Commented Nov 22, 2016 at 20:27
  • 1
    You have a more complex object it seems. json.data[0].itemName Commented Nov 22, 2016 at 20:27
  • Do you need to use json.parse, isn't it already a json Commented Nov 22, 2016 at 20:28
  • @Hosar i have JSON.parse, just didn't bothered to type it in uppercase Commented Nov 22, 2016 at 20:52

2 Answers 2

2

Your data looks like this:

{
  "data": [
    {
      "_id": "5834551dfa44228b52645f43",
      "itemDesc": "lorem ipsum dolor sit amet",
      "itemName": "test item",
      "__v": 0
    }
  ]
}

Your JSON object has one property called data.

data is an array with one element.

That element is a object with four parameters.

So the values you want are available like this:

let data = '{"data":[{"_id":"5834551dfa44228b52645f43","itemDesc":"lorem ipsum dolor sit amet","itemName":"test item","__v":0}]}';
let json = JSON.parse(data);
let name = json.data[0].itemName;
Sign up to request clarification or add additional context in comments.

1 Comment

ouch, i thought data is payload that comes within a call and everything inside is an actual body. that works now.. thanks
2

You are using the same var name for json var json = json.parse(data); you should be using a different name i.e. parsedJson or something like that, you should also use JSON.pase if you intend to use the code in a case sensitive OS

Comments

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.