Reputation:
So, I know how to read a "single-level" json array. However, I can't figure out how to index the value I want from a multi-level json array.
I have this JSON data:
{
"items": [
{
"snippet": {
"title": "YouTube Developers Live: Embedded Web Player Customization"
}
}
]
}
I would like to access the value of title, however neither of these access the value, but instead return undefined:
console.log(data["items"][0].title);
or:
console.log(data["items"][0]["title"]);
But, this code returns the snippet
object:
console.log(data["items"][0]);
The data
variable refers to the json data.
How should I go about this?
Upvotes: 0
Views: 6314
Reputation: 2175
As addition to madox2's answer, here's an explanation:
{
"items": [
{
"snippet": {
"title": "YouTube Developers Live: Embedded Web Player Customization"
}
}
]
}
The root is a Object, while items
is an array. Objects are surrounded by curly braces, while arrays are surrounded by sqare braces.
In JS, you can access a Object like this:
parent.child
In your case, assuming you the data is assigned to a variable called data
, you would access it with the variable name and the object you want to get:
data.items
Array's have keys - if no keys are specified, the keys will be number-based.
So seeing that items
is an array without any key specified, you'll have to access the x-th element. x
is in your case 0, because it's the first item of the array (Remember, arrays are zero-indexed):
data.items[0]
And here you have a object again, so access it:
data.items[0].snippet.title
Upvotes: 2
Reputation: 51881
Try this:
data.items[0].snippet.title
Explanation (you can see corresponding object in /* */
comment):
items[0];
/*
{
'snippet': {
'title': 'YouTube Developers Live: Embedded Web Player Customization'
}
}
*/
items[0].snippet;
/*
{
'title': 'YouTube Developers Live: Embedded Web Player Customization'
}
*/
items[0].snippet.title;
/*
'YouTube Developers Live: Embedded Web Player Customization'
*/
Upvotes: 5