5

a web service returns the following nested json object:

{"age":"21-24","gender":"Male","location":"San Francisco, CA","influencer score":"70-79","interests":{"Entertainment":{"Celebrities":{"Megan Fox":{},"Michael Jackson":{}},},"Social Networks & Online Communities":{"Web Personalization": {},"Journals & Personal Sites": {},},"Sports":{"Basketball":{}},},"education":"Completed Graduate School","occupation":"Professional/Technical","children":"No","household_income":"75k-100k","marital_status":"Single","home_owner_status":"Rent"}

i just want to iterate through this object without specifying property name, i tried the following code :

for (var data in json_data) {
    alert("Key:" + data + " Values:" + json_data[data]);
}

however it prints value as [object Object] if it's a nested value, is there any way to keep iterating deeper into nested values ?

6 Answers 6

7

Try this:

function iter(obj) {
  for (var key in obj) {
    if (typeof(obj[key]) == 'object') {
      iter(obj[key]);
    } else {
      alert("Key: " + key + " Values: " + obj[key]);
    }
  }
}

BB: added + to prevent error.

Sign up to request clarification or add additional context in comments.

1 Comment

typeof(someObject) returns "object" not "Object"...Note the lowercase "o"
3

You can do this recursively.

function alertobjectKeys(data) {
  for (var key in data) {
    if (typeof(data[key]) == "object" && data[key] != null) {
      alertobjectKeys(data[key]);
    } else {
      alert("Key:" + key + " Values:" + data[key]);
    }
  }
}

1 Comment

Inside your nested call you need data[key] - otherwise you're simply reiterating the same object you received.
0

This of course requires recursion

(function(obj) {
  for (var key in obj) if (obj.hasOwnProperty(key)) {
    if (typeof obj[key] == 'object' && obj[key] !== null)
      arguments.callee(obj[key]);
    else 
      alert("Key: " + key + " Values: " + obj[key]);
  }
)(json_data));

1 Comment

Doesn't require recursion, but recursion can help if your data isn't ridiculously large.
0
function recursiveParse(variable) { 
    for (var key in variable) {
        if ((is_object(variable[key])) || (is_array(variable[key]))) {
            recursiveParse(variable[key]);
        } else {
            // Process variable here
        }
    }
}

Then just call that function with the parameter being the json data, it will parse through the remaining objects and arrays recursively.

2 Comments

where are the definition for is_object() and is_array() ?
In another library I forgot to tell you about but am so used to that I forgot it wasn't core javascript. I apologize.
0

You can always create a recursive function:

function alertObj(obj) {
    for (var data in obj) {
        if(typeof(obj[data]) === "object")
            alertObj(obj[data]);
        else
            alert("Key:" + data + " Values:" + obj[data]);
    }
}

As long as you aren't worried about recursing too far (which you probably don't need to with JSON objects).

You can also do this with a queue or stack (array) structure:

function alertObj_queue(obj) { // Breadth-first
    var arrPrint = [{key:"Object", data:obj}]; // Initialize array with original object

    for(var i = 0; i < arrPrint.length; i++) {
        if(typeof(arrPrint[i].data) === "object") {
            for(var k in arrPrint[i].data) { // Add each to end of array
                arrPrint.push({key: k, data: arrPrint[i].data[k]});
            }
            alert("Object key: " + arrPrint[i].key);
        } else {
            alert("Key:" + arrPrint[i].key + " Values:" + arrPrint[i].data);
        }
    }
}

function alertObj_stack(obj) { // Depth-first
    var arrPrint = [{key:"Object", data:obj}]; // Initialize array with original object

    while(arrPrint.length) {
        var o = arrPrint.pop();
        if(typeof(o.data) === "object") {
            for(var k in o.data) { // Add each to end of array
                arrPrint.push({key: k, data: o.data[k]});
            }
            alert("Object key: " + o.key);
        } else {
            alert("Key:" + o.key + " Values:" + o.data);
        }       
    }
}

3 Comments

your code is not right. You pass in obj but use json_data in your for loop....json_data is undefined.
unfortunately both does not work, they only go through the 1st level
@HeoQue: You only see alerts on the first level because in your data, everything below the first level is an object, so the loop will look at "Sports" and see that it's an object, then go down to "Basketball" and see that it's also an object, so it won't alert for any of those. It would probably make things easier to have some of your JSON data as arrays ("Sports", "Celebrities", etc.).
0

I'm guessing that in your request (assuming it's Ajax) you aren't specifying the dataType to be returned as 'json'.

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.