簡體   English   中英

如何訪問JSON對象中的對象數組?

[英]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 keysvalues在引號內的事實有關嗎? (我實際上無法編輯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);

試試這個http://jsfiddle.net/6uhp6y34/

你可以使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM