Looping through JSON arrays

I'm trying to pull the field names in the header of some JSON output. The following is a sample of the JSON header info:

{"HEADER":{"company":{"label":"Company Name"},"streetaddress":{"label":"Street Address"},"ceo":{"label":"CEO Name","fields":{"firstname":{"label":"First Name"},"lastname":{"label":"Last Name"}}}

I'm able to loop through the header and output the field and label (i.e. company and Company Name) using the following code:

obj = JSON.parse(jsonResponse);

for (var key in obj.HEADER) {
    response.write ( obj.HEADER[key].label );
    response.write ( key );
}

but can't figure out how to loop through and output the sub array of fields (i.e. firstname and First Name).

Any ideas?

Answers


Try this?

obj = JSON.parse(jsonResponse);

for (var key in obj.HEADER) {
    response.write ( obj.HEADER[key].label );
    response.write ( key );
    if (obj.HEADER[key].fields) {
        for (var fieldKey in obj.HEADER[key].fields) {
            response.write(obj.HEADER[key].fields[fieldKey].label);
            response.write(fieldKey);
        }
    }
}

Or, if the fields themselves can have even more fields, try recursion:

function parseResults(obj) {
    for (var key in obj) {
        response.write ( obj[key].label );
        response.write ( key );
        if (obj[key].fields) {
            parseResults(obj[key].fields);
        }
    }
}

obj = JSON.parse(jsonResponse);
parseResults(obj.HEADER);

Need Your Help

How can I generate a String Array for a ListView using conditionals to determine if the String elements should be on the List?

android arrays listview if-statement tabview

This is my first question on the site and I hope it's not too embarrassing. I'm making an Inventory tab for an Android game. I've declared static variables at the beginning of my class and based on