Locotes
Locotes

Reputation: 91

Parsing nested JSON without using getJSON()

I know there are a hundred "parse json" questions already out there - but I couldn't find one with a solution that matched my own situation.

I receive JSON similar to this:

{    
"parent:array": [
    {
        "child:value": "test1",
        "child:array": [
            {
                "child:subvalue": "test3"
            }
        ]
    },
    {
        "child:value": "test2",
        "child:array": [
            {
                "child:subvalue": "test4"
            }
        ]
    }
]
}

I can access child:value by doing the following (where response is the JSON):

var parameters = response['parent:array'];
$.each(parameters, function (idx, data) {
    var childValue = data['child:value'];
});

However, I haven't been able to retrieve child:subvalue yet. Can it be done as part of the each?

I tried the following approaches without success:

response['parent:array']['child:array']

and...

var childSubvalue = data['child:array']['child:subvalue'];

Upvotes: 0

Views: 153

Answers (3)

Neil S
Neil S

Reputation: 2304

once your json is valid:

$.each(parameters, function (idx, data) {
    var childValue = data['child:value'], childArray = data['child:array'];
    $.each(childArray, function(i, d) {
        alert(d['child:subvalue']);
    });
});

Fiddle

Upvotes: 1

Lars Anundskås
Lars Anundskås

Reputation: 1355

iterate through the outer and inner arrays with array.forEach;

var json = {    
"parent:array": [
    {
        "child:value": "test1",
        "child:array": [
            {
                "child:subvalue": "test3",
            }
        ]
    },
    {
        "child:value": "test2",
        "child:array": [
            {
                "child:subvalue": "test4"
            }
        ]
    }
]
}

json["parent:array"].forEach(function(parent) {
    console.log(parent["child:value"]);
    parent["child:array"].forEach(function(child) {
        console.log(child["child:subvalue"]);
    });
});

Upvotes: 0

Simon Boudrias
Simon Boudrias

Reputation: 44589

"child:array" is an array, so you need to give an index to select, like so:

var childSubvalue = data['child:array'][0]['child:subvalue'];

Upvotes: 2

Related Questions