Marcin Buglewicz Marcin Buglewicz - 1 year ago 153
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 which returns an array as you'd expected:

{"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;

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

Answer Source

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 =[0].itemName;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download