Web服务返回以下嵌套的json对象:
{"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"}
我只想遍历此对象而不指定属性名称,我尝试了以下代码:
for (var data in json_data) { alert("Key:" + data + " Values:" + json_data[data]); }
但是,如果它是嵌套值,则将值打印为[object Object],是否有任何方法可以使迭代更深入嵌套值?
试试这个:
function iter(obj) { for (var key in obj) { if (typeof(obj[key]) == 'object') { iter(obj[key]); } else { alert("Key: " + key + " Values: " + obj[key]); } } }
BB:添加了+以防止错误。