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],有没有办法让迭代更深入嵌套值?
答案 0 :(得分:7)
试试这个:
function iter(obj) {
for (var key in obj) {
if (typeof(obj[key]) == 'object') {
iter(obj[key]);
} else {
alert("Key: " + key + " Values: " + obj[key]);
}
}
}
BB:添加+以防止错误。
答案 1 :(得分:3)
你可以递归地做到这一点。
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]);
}
}
}
答案 2 :(得分:0)
您始终可以创建递归函数:
function alertObj(obj) {
for (var data in obj) {
if(typeof(obj[data]) === "object")
alertObj(obj[data]);
else
alert("Key:" + data + " Values:" + obj[data]);
}
}
只要你不担心递归过多(你可能不需要使用JSON对象)。
您也可以使用队列或堆栈(数组)结构执行此操作:
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 :(得分:0)
这当然需要递归
(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));
答案 4 :(得分: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
}
}
}
然后只使用参数为json数据调用该函数,它将递归地解析剩余的对象和数组。
答案 5 :(得分:0)
我猜你的请求(假设它是Ajax)你没有指定dataType作为'json'返回。