我正在尝试使用以下代码遍历 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
问题是我的JSON是一个字符串而不是一个对象。以下是解决它的代码:
JSON.parse(jsonString);