嘿伙计们我想解析这种类型的字符串:
{"1":
[
{"OrderItemId":832,"ItemId":995,"Price":0},
{"OrderItemId":833,"ItemId":997,"Price":0},
{"OrderItemId":834,"ItemId":999,"Price":0}
],
"2":
[
{"OrderItemId":835,"ItemId":1008,"Price":0},
{"OrderItemId":836,"ItemId":1057,"Price":0}
]
}
对我来说非常重要,所以请大家帮助我。
答案 0 :(得分:4)
像这样,如果你想访问OrderItemId
var test = {"1":
[
{"OrderItemId":832,"ItemId":995,"Price":0},
{"OrderItemId":833,"ItemId":997,"Price":0},
{"OrderItemId":834,"ItemId":999,"Price":0}
],
"2":
[
{"OrderItemId":835,"ItemId":1008,"Price":0},
{"OrderItemId":836,"ItemId":1057,"Price":0}
]
}
alert(test["1"][0]['OrderItemId']);
alert(test["1"][1]['OrderItemId']);
alert(test["1"][2]['OrderItemId']);
alert(test["2"][0]['OrderItemId']);
alert(test["2"][1]['OrderItemId']);
更新,以未知长度迭代测试
for (var i=0;i<test["1"].length;i++) {
alert(test["1"][i]['OrderItemId']);
}
这里有全自动装载
var number, count = 0;
var en = [];
for(number in test) {
en[count]=number;
count++;
}
for (var r=0;r<en.length;r++) {
alert(en[r]);
for (var i=0;i<test[en[r]].length;i++) {
alert(test[en[r]][i]['OrderItemId']);
}
}
答案 1 :(得分:3)
答案 2 :(得分:2)
//您也可以这样做:
<script>
var employees = { "accounting" : [ // accounting is an array in employees.
{ "firstName" : "John", // First element
"lastName" : "Doe",
"age" : 23 },
{ "firstName" : "Mary", // Second Element
"lastName" : "Smith",
"age" : 32 }
], // End "accounting" array.
"sales" : [ // Sales is another array in employees.
{ "firstName" : "Sally", // First Element
"lastName" : "Green",
"age" : 27 },
{ "firstName" : "Jim", // Second Element
"lastName" : "Galley",
"age" : 41 }
] // End "sales" Array.
} // End Employees
var output="<ul>";
for (var i in employees.accounting) {
output+="<li>" + employees.accounting[i].firstName + " " + employees.accounting[i].lastName + "--" + employees.accounting[i].age+"</li>";
}
output+="</ul>";
var output1="<ul>";
for (var j in employees.sales) {
output1+="<li>" + employees.sales[j].firstName + " " + employees.sales[j].lastName + "--" + employees.sales[j].age+"</li>";
}
output+="</ul>";
alert(output1);
</script>
答案 3 :(得分:0)
问题可能是由于行结束。
这是一个有效的[在chrome dev控制台中测试]代码:
var jsonStr = '{"1":\
[\
{"OrderItemId":832,"ItemId":995,"Price":0},\
{"OrderItemId":833,"ItemId":997,"Price":0},\
{"OrderItemId":834,"ItemId":999,"Price":0}\
],\
"2":\
[\
{"OrderItemId":835,"ItemId":1008,"Price":0},\
{"OrderItemId":836,"ItemId":1057,"Price":0}\
]\
}';
var obj = JSON.parse(jsonStr); // works!
答案 4 :(得分:0)
您可以使用jQuery to Parse JSON
另请查看此SO问题Parse JSON in JavaScript?
答案 5 :(得分:0)
如果每个对象项都结束,则无需在结束后添加反斜杠。您只能用逗号分隔。