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 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.