简体   繁体   中英

Access / process (nested) objects, arrays in JSON using AJAX JQuery

I have a (nested) data structure containing objects and arrays. How can I extract the information, ie access a specific or multiple values (or keys) like 1, 105 ,1055?

For example:

[{"1":{"url":"http:\/\/web.com\/","catname":"HOBBIES"}},
{"105":{"parent":"1","url":"http:\/\/web.com\/","catname": "TRUCKS"}},
{"1055":{"parent":"105","url":"http:\/\/web.com\/","catname":"TIRES"}} ]

Code is :

$( document ).ready(function() {
var formURL = 'http://web.com/ajax.php?store=photo&action=jsoncategories';
        $.getJSON( formURL, function(json) {
        $.each(json[0], function(i, object) {
              $.each(object, function(property, value) {
              console.log(property + "=" + value);
              });
           });
        });
});

json[0] is traversing data for key 1. What should replace json[0] to extract all data keys of array

you are missing a " before TRUCK. Also, try using console.log(property + "=" + value); instead of alert().

$.each(json, function(key, val) {
    $.each(val, function(index, value){
         console.log(value);
    });
});

or maybe like so:

$.each(json, function(key, val) {
    $.each(val, function(key, val) {
        console.log(val.url);
    });
});

Here is traversing using JavaScript over your elements. I assume that data was loaded and and traversing starts in your code as follows:

var json = [{"1":{"url":"http:\/\/web.com\/","catname":"HOBBIES"}},
{"105":{"parent":"1","url":"http:\/\/web.com\/","catname": "TRUCKS"}},
{"1055":{"parent":"105","url":"http:\/\/web.com\/","catname":"TIRES"}} ];



for(var i=0, json_len=json.length; i< json_len; i+=1)
{
    var j = json[i]; // Here you are accessing to the item of Array using index of item.
    for(var k in j)
    {
       var d=j[k]; //Here you are accessing to the object using key pair.
       for(var l in d)
           console.log( k, ':', l, ':', d[l]);
    }
}

You can see sample code execution in JSFIDDLY .

If you have long json array this approach better. Because your json variable is Array and traversing among elements of array should be done using for loop. Your items of array is objects so they should be traversed using for ... in . This is best approach to keep in mind. Because for loop is faster than each . Here is comparison in jsperf. If you have question feel free to leave comment here.

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