简体   繁体   中英

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 Structure:

{
    "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...

    $.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.

(Naturally, using farm.items[1].name to target the first name didn't work either.)

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? (I can't actually edit the JSON feed as it's external).

How can I simply target the nested array and grab items I want and their properties?

You have error in your JSON structure. Your JSON need to be:

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/

you can use $eaach function of jquery as

$.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

data= 'get ur  json'
for ( i in data.items ) {
   console.log ( i.name + "" )
   console.log ( i.description + "" );    
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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