[英]How can I access an array of objects within a JSON object?
如何访问位于数组中的对象,该数组本身位于JSON对象中?
JSON结构:
{
"name":"animals",
"type":"farmyard",
"version": "1.0",
"items": [{
{
"name": "pig",
"description": "pink, round"
},
{
"name": "chicken",
"description": "small, yellow"
}
}]
}
到目前为止这里是JS ......
$.getJSON( "https://_LINK_TO_JSON.json", function( data ) {
var farm = [];
var animals = [];
$.each( data, function( key, val ) {
farm.push(key, val);
var animals = farm[3];
console.dir(animals);
});
console.dir(animals);
});
我曾尝试使用farm.items
来定位数组,但这不起作用所以我使用了索引号。
(当然,使用farm.items[1].name
来定位名字也不起作用。)
我不能只使用点符号与JSON keys
和values
在引号内的事实有关吗? (我实际上无法编辑JSON提要,因为它是外部的)。
我怎样才能简单地定位嵌套数组并获取我想要的项目及其属性?
您的JSON结构中有错误。 你的JSON需要是:
var data = {
'name':'animals',
'type':'farmyard',
'version': '1.0',
'items': [
{
'name': 'pig',
'description': 'pink, round'
},
{
'name': 'chicken',
'description': 'small, yellow'
}
]
};
console.log(data.items);
你可以使用jquery的$ eaach函数作为
$.getJSON (urltoJSON, function(data){
$.each(data.response.venue.items, function (index, value) {
console.log(this.name);
console.log(this.description);
});
});
你也可以将json保存在一个javascript变量中并迭代它
data= 'get ur json'
for ( i in data.items ) {
console.log ( i.name + "" )
console.log ( i.description + "" );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.