0

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

4
  • 4
    You need to parse it as JSON. Commented Nov 18, 2016 at 17:15
  • 2
    ^^ E.g., data = JSON.parse(data) as the first line of your callback. Commented Nov 18, 2016 at 17:17
  • @SLaks why to need parse json when it is already json Commented Nov 18, 2016 at 17:26
  • 2
    @Mahi: It's a string. If you want an object, you need to parse the string. Commented Nov 18, 2016 at 17:30

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

I also had to change the data variable to a different name like resp_data, because the variable inside my json was also called data and it was giving me conflicts...
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.