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. I am using nodejs so it has to be javascript.
So far when I run the following I get a nice json response.
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
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. 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. 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?
Loop over json.followers.length
- not json.length
- json
is an object, and objects don't have a length:
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. But here json.follows is an array. So we should use for loop.
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);
for (var j = 0; j < obj.follows.length; j++) {
var thisName = jsonObj.follows[j].user.name;
console.log(thisName);
}