[英]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. 我想知道为什么当我尝试在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: 来自api的json:
{
"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} {“ data”:[{所有数据都显示在这里}],“ paging”:0}
undefined 未定义
undefined 未定义
undefined 未定义
Looks like your route is returning the stringified JSON. 看起来您的路线正在返回字符串化的JSON。
Try 尝试
jsonData = JSON.parse(data)
console.log(jsonData)
console.log(jsonData.data)
console.log(jsonData.paging)
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 因为您的结果清楚地表明它是一个字符串,所以您需要按照上述答案进行解析
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.