Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing nested JSON without using variable names

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 ?

like image 647
Amr Ellafy Avatar asked Nov 05 '10 20:11

Amr Ellafy


1 Answers

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.

like image 123
g.d.d.c Avatar answered Oct 07 '22 13:10

g.d.d.c