[英]JSON loop a multidimensional array to with node.js
Having read up on different methods please bear with me to try to explain. 阅读了不同的方法后,请允许我尝试解释。
I am trying to retreive data from the twitch api and loop the user.name results to an array possibly inside an object. 我正在尝试从twitch api中检索数据,并将user.name结果循环到可能在对象内部的数组。 I am using nodejs so it has to be javascript.
我正在使用nodejs,所以它必须是javascript。
So far when I run the following I get a nice json response. 到目前为止,当我运行以下命令时,我会收到一个不错的json响应。
var request = require('request');
request({url: 'https://api.twitch.tv/kraken/channels/twitch/follows?limit=3'}, function(err, res, json) {
if (err) {
throw err;
}
console.log(json);
});
this then logs the same as if one where to visit https://api.twitch.tv/kraken/channels/twitch/follows?limit=3 然后,它记录的内容与访问https://api.twitch.tv/kraken/channels/twitch/follows?limit=3的位置相同
or better visualized as 或更好地可视化为
Now I want to select the follows -> user -> name object. 现在,我要选择以下->用户->名称对象。 More so, loop every user -> name in the response.
更重要的是,在响应中循环每个用户->名称。
I thought I would need to convert the string to an object so I tried 我以为我需要将字符串转换为对象,所以我尝试了
var obj = JSON.parse(json);
but that only returns the first {3} objects in the tree. 但这仅返回树中的前{3}个对象。 So I went ahead and tried
所以我继续尝试
var request = require('request');
request({url: 'https://api.twitch.tv/kraken/channels/twitch/follows?limit=3'}, function(err, res, json) {
if (err) {
throw err;
}
for (var i=0; i<json.length; i++) {
var obj = JSON.parse(json.follows[i].user.name);
console.log(obj);
}
});
and it returns 它返回
TypeError: Cannot read property '0' of undefined
For testing purposes I also got rid of the loop and just have 1 to return one bit of info. 出于测试目的,我也摆脱了循环,只用1来返回一点信息。 Having tried multiple instances of rearranging the call I always get either an error or "undefined" back.
尝试过多次重新安排呼叫的实例后,我总是会收到错误消息或“未定义”消息。
Nothing seems to work, I am even going about this the right way? 似乎没有任何效果,我什至正在以正确的方式进行操作?
循环遍历json.followers.length
而不是json.length
- json
是一个对象,并且对象没有长度:
for (var i=0; i<json.follows.length; i++) {
As json is an object here, we should use for-in though there is no length property. 由于json是此处的对象,因此我们应该使用for-in,尽管没有length属性。 But here json.follows is an array.
但是这里json.follows是一个数组。 So we should use for loop.
因此,我们应该使用for循环。
var len = json.follows.length;
for (var i=0; i< len; i++) {
console.log(json.follows[i].user.name);
}
Supposing you do var obj = JSON.parse(json);
假设您执行
var obj = JSON.parse(json);
for (var j = 0; j < obj.follows.length; j++) {
var thisName = jsonObj.follows[j].user.name;
console.log(thisName);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.