Marcin Buglewicz Marcin Buglewicz - 12 days ago 8
Javascript Question

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?

Answer

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