Gustavo Gabriel
Gustavo Gabriel

Reputation: 1296

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

Upvotes: 0

Views: 943

Answers (2)

Alaguvel
Alaguvel

Reputation: 46

when you console it, if it is a Object it should be displayed as below

Object {data: Array[2], paging: 0}

as your result shows clearly that it's a string so you need to parse it as told by the above answers

Upvotes: 0

samdenicola
samdenicola

Reputation: 26

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)

Upvotes: 1

Related Questions