简体   繁体   English

如何访问JSON对象中的对象数组?

[英]How can I access an array of objects within a JSON object?

How can I access objects that sit within an array, which is itself inside a JSON object? 如何访问位于数组中的对象,该数组本身位于JSON对象中?

JSON Structure: JSON结构:

{
    "name":"animals",
    "type":"farmyard",
    "version": "1.0",

    "items": [{
        {
            "name": "pig",
            "description": "pink, round"
        },

        {
            "name": "chicken",
            "description": "small, yellow"
        }
    }]

}

And here is the JS so far... 到目前为止这里是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);

    });

I've tried to use farm.items to target the array, but that didn't work so I've used the index number instead. 我曾尝试使用farm.items来定位数组,但这不起作用所以我使用了索引号。

(Naturally, using farm.items[1].name to target the first name didn't work either.) (当然,使用farm.items[1].name来定位名字也不起作用。)

Is the reason I can't just use dot notation something to do with the fact that JSON keys and values are within quote marks? 我不能只使用点符号与JSON keysvalues在引号内的事实有关吗? (I can't actually edit the JSON feed as it's external). (我实际上无法编辑JSON提要,因为它是外部的)。

How can I simply target the nested array and grab items I want and their properties? 我怎样才能简单地定位嵌套数组并获取我想要的项目及其属性?

You have error in your JSON structure. 您的JSON结构中有错误。 Your JSON need to be: 你的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);

Try this http://jsfiddle.net/6uhp6y34/ 试试这个http://jsfiddle.net/6uhp6y34/

you can use $eaach function of jquery as 你可以使用jquery的$ eaach函数作为

$.getJSON (urltoJSON, function(data){
$.each(data.response.venue.items, function (index, value) {
    console.log(this.name);
    console.log(this.description);
 });
});

also you can save the json in a javascript variable and iterate over it as 你也可以将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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM