-4
So. I’m working with the Youtube api to give GET the number of subscribers on a channel. All right. json gets to the code, my only problem is trying to get the value of the key subscriberCount.
The json that is returned:
{
"kind": "youtube#channelListResponse",
"etag": "ji3OqKq0t01wxWAUgA2LLg5GR8Q",
"pageInfo": {
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#channel",
"etag": "37_CPNyQ9CbrVL8e1YBzPufbOUE",
"id": "UCasElAZ8Fn1ACje99uyQK5g",
"statistics": {
"viewCount": "63842823",
"commentCount": "0",
"subscriberCount": "228000",
"hiddenSubscriberCount": false,
"videoCount": "349"
}
}
]
}
This is my code:
let url = "https://www.googleapis.com/youtube/v3/channels?part=statistics&id=" + id_canal + "&key=" + config.youtubetoken
request(url, function (error, response, body) {
console.log(body.items[0].statistics.subscriberCount);
});
and my mistake is this:
console.log(body.items[0].statistics.subscriberCount);
^
TypeError: Cannot read property '0' of undefined
I tried support in the American stack overflow, but they gave me a simple "duplicate topic" when the topic had nothing to do with mine. Please help me out.
Thank you, Gustavo.
Ever tried to give a
console.log(body)
to see what you’re actually trying to access? The error itself tells exactly what’s going on -TypeError: Cannot read property '0' of undefined
shows thatbody.items
isundefined
. Because of that, you can’t dobody.items[0]
. It’s the same thingundefined[0]
. Hence the importance of giving theconsole.log
or some other form of debug. The structure ofbody
probably not what you expect.– Luiz Felipe
it seems that you receive an object and not an array, take the
[0]
and see ifbody.items.statistics.subscriberCount
gives you something back.– Colasanto
@Colasanto He gives me an error. http://prntscr.com/us5umj
– Gustavo
@Luizfelipe this is the body returned by the api and sent to the console: http://prntscr.com/us5uzk
– Gustavo
and body as @Luizfelipe said ? returns something ?
– Colasanto
typeof body
isobject
orstring
?– Luiz Felipe
@Luizfelipe
string
(http://prntscr.com/us5xqs -- http://prntscr.com/us5xtu)– Gustavo
There’s the problem. Convert the
string
for JSON or hitrequest
to provide the data in the appropriate type.– Luiz Felipe
I was at 3 o'clock in the afternoon wondering what the problem might be, and you solved it in 11 minutes. Really, it helped a lot :) @Luizfelipe
– Gustavo
items
is an array, you need to iterate (for example) to read the values, or use the index:body.items[0].statistics
– Ricardo Pontual