luee luee - 6 months ago 7
Node.js Question

Retrive single data from json object in nodejs

i am new in nodejs . i tried the below code for retriving json object. but i can't retrive a single data from json object

My code is

function getData(){
var http = require('http');
var qs = require('querystring');
var str = '';

var options = {
host: '192.168.1.16',
port: 8080,
path: '/courseapi/view'
};

callback = function(response) {

response.on('data', function (chunk) {
str += chunk;
});

response.on('end', function () {
console.log(str);
console.log(str[0]._id);
});
}

var req = http.request(options, callback).end();
};


i tried this str[0]._id but it return undefined

Answer

Try:

response.on('end', function () {
  str = JSON.parse(str);
  console.log(str);
  console.log(str[0]._id);
});