views:

43

answers:

1

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?

+1  A: 

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);
Bob
worked perfectly, thanks!
George