我正在尝试使用以下代码迭代JSON对象:
traverse(json, process);
//called with every property and it's value
function process(key, value) {
console.log(key + " : " + value);
}
function traverse(o, func) {
for (var i in o) {
func.apply(this, [i, o[i]]);
if (o[i] !== null && typeof (o[i]) == "object") {
//going on step down in the object tree!!
traverse(o[i], func);
}
}
}
这是JSON对象:
{"breakfast_menu":{"food":[{"name":["Belgian Waffles"],"price":["$5.95"],"description":["Two of our famous Belgian Waffles with plenty of real maple syrup"],"calories":["650"]},{"name":["Strawberry Belgian Waffles"],"price":["$7.95"],"description":["Light Belgian waffles covered with strawberries and whipped cream"],"calories":["900"]},{"name":["Berry-Berry Belgian Waffles"],"price":["$8.95"],"description":["Light Belgian waffles covered with an assortment of fresh berries and whipped cream"],"calories":["900"]},{"name":["French Toast"],"price":["$4.50"],"description":["Thick slices made from our homemade sourdough bread"],"calories":["600"]},{"name":[ "Homestyle Breakfast"],"price":["$6.95"],"description":["Two eggs, bacon or sausage, toast, and our ever-popular hash browns"],"calories":["950"]}]}}
它为我打印的结果如下:
> 748 : s
> 749 : t
> 750 : ,
> 751 :
> 752 : a
> 753 : n
> 754 : d
> 755 :
> 756 : o
> 757 : u
> 758 : r
> 759 :
> 760 : e
> 761 : v
> 762 : e
> 763 : r
> 764 : -
> 765 : p
我的预期结果是打印像
这样的值> key : value
答案 0 :(得分:0)
问题是我的JSON是一个字符串而不是一个对象。以下是解决它的代码:
JSON.parse(jsonString);