admin管理员组文章数量:1334133
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?
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?
Share Improve this question edited Feb 3, 2016 at 17:05 Asons 87.3k12 gold badges117 silver badges174 bronze badges asked Feb 3, 2016 at 16:37 user5773800user57738002 Answers
Reset to default 5Try this:
data.items[0].snippet.title
Explanation (you can see corresponding object in /* */
ment):
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'
*/
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
本文标签: javascriptHow to read multilevel jsonStack Overflow
版权声明:本文标题:javascript - How to read multi-level json - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742280251a2445960.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论