techlead
techlead

Reputation: 779

Looping JSON structure using jQuery

JSON

{
    "form": {
        "roles": {
          "role": [
            { "name": "RoleB" },
            { "name": "RoleA" }
          ]
        },
        "rows":[
            {
                "id":"1",                               
                "fields":{              
                    "field":[
                        {
                            "fname":"Matt"
                        }
                    ]
                }
            }
        ]
    }
}

How can I access the value of fname using jquery?

This is what I'm doing --

jQuery.each(response.form.rows.fields.field, function(i, val){
     alert(this.fname);
}

Upvotes: 1

Views: 438

Answers (1)

Blazemonger
Blazemonger

Reputation: 92893

Watch out for those arrays....

response.form.rows[0].fields.field[0].fname

Or, in your case (and assuming there's only one rows element):

jQuery.each(response.form.rows[0].fields.field, function(i, val){
     alert(this.fname);
});

If there's more than one element in rows, you need a second loop:

jQuery.each(response.form.rows, function() {
    jQuery.each(this.fields.field, function(i, val) {
        alert(val.fname);
    });
});

http://jsfiddle.net/mblase75/33H8L/

Upvotes: 3

Related Questions