Gustavo Gabriel Gustavo Gabriel - 18 days ago 9
Javascript Question

Variable undefined when getting json from api

I wanna know why is it giving me undefined when I try to get a variable inside my json.

Here's the code I am executing:

var options = {
host: url,
path: '/api/v1/outside_processes/active_companies?process_token=' + process_token,
method: 'POST'
};

http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (data) {
console.log(data);
console.log(data.data);
console.log(data["data"]);
console.log(data.paging);
});
}).end();


The json coming from the api:

{
"data": [
{
"id": 37
...more data
},
{
"id": 15,
...more data
}
],
"paging": 0
}


What i am getting in the console:

{"data":[{ all the data is showing here }],"paging":0}

undefined

undefined

undefined

Answer

Looks like your route is returning the stringified JSON.

Try

jsonData = JSON.parse(data)
console.log(jsonData)
console.log(jsonData.data)
console.log(jsonData.paging)