简体   繁体   中英

Iterating Nested JSON to array of objects (JavaScript)

Hi I get a JSON response like this:

{
"20150917":
 {
     "Daily01sec":
        {
            "TG01152600000": "\/20150917\/Daily01sec\/TG0115260.bin",
            "TG01152600600": "\/20150917\/Daily01sec\/TG0115260.bin"
        }
    },
"201510":
    {
        "05":
        {
            "Daily01sec":
            {
                "TG01152780600": "\/201510\/05\/Daily01sec\/TG01152780600.bin"                       
            }
        }
    },
"201509":
    {
        "05":
        {
            "Daily01sec":
            {
                "TG01152780600": "\/201510\/05\/Daily01sec\/TG01152780600.bin"                     
            }
        }
    }
}

I want an array of indexes of and its value to the corresponding data.

I want to have data["20150917"],data["201510"],data["201509"] and the corresponding information for it.

Actually the nested data would be an array of nested data in it,

Can be parsed with angularJS ng-repeat? any idea?

In JavaScript an object is an associative array.

In other words myobj.data is the same thing as myobj['data'] - the two can be used interchangeably. So all you have to do is parse your JSON (if it's not already) and you're good to go.

data = JSON.parse(json); 
console.log(data['20150917']);

http://jsfiddle.net/byjawop8/

EDIT

You're looking for for..in syntax, which looks like this:

for(index in json){
    document.getElementById('r').insertAdjacentHTML('beforeEnd', index+" " + json[index]['05']['Daily01sec']['TG01152780600'] + "<br>");
}

http://jsfiddle.net/yjedwLws/1/

EDIT AGAIN

I gave you what you needed in my last edit, but I'll give you one more hint. This function iterates through the JSON, and as long as it's formatted in the way you posted above, this will convert the whole thing into an array you can easily iterate through.

function arrayConvert(json){
    var arr = [];
    for(index in json){
        var obj = json[index];
        var key = null;
        while(typeof obj == 'object'){
            for(ind in obj){
                if(key == null) key = ind;
                obj = obj[ind];
            }
        }
        arr.push({'key':key, 'val':obj});
    }
    return arr;
}

And another fiddle: http://jsfiddle.net/yjedwLws/2/

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