Marcin Buglewicz
Marcin Buglewicz

Reputation: 77

How to get object from json file in node.js?

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?

Upvotes: 0

Views: 1157

Answers (2)

Dave
Dave

Reputation: 1987

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;

Upvotes: 2

nottu
nottu

Reputation: 379

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

Upvotes: 2

Related Questions