javascript 如何在 jQuery 中解析 JSON 多维数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10881429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I parse a JSON multidimensional array in jQuery?
提问by Akhil Jain
Here is my JSON which I need to parse:
这是我需要解析的 JSON:
{"opcode":"groupdetails",
"status":"success",
"data":[{"Group ID":5,"Group Name":"data structure","Group Subject":"computer science","Role Type":"Teacher"},{"Group ID":4,"Group Name":"information technology","Group Subject":"computer science","Role Type":"Student"},{"Group ID":6,"Group Name":"data mining","Group Subject":"computer science","Role Type":"Parent"},{"Group ID":7,"Group Name":"dccn","Group Subject":"computer science","Role Type":"Teacher"}]}
I have tried and implemented the solution provided hereand this is the implementation of JS that was defined in there solution, which parses only the JSON array
我已经尝试并实现了此处提供的解决方案,这是在该解决方案中定义的 JS 的实现,它仅解析 JSON 数组
for (var i = 0; i < data.data.length; i++)
{
var object = data.data[i];
for (property in object)
{
var value = object[property];
alert(property + "=" + value);
}
}
the outer JSON datais returned from server and yes I have tried parsing using the following code and there is no result:
外部 JSON数据从服务器返回,是的,我尝试使用以下代码进行解析,但没有结果:
for (var i = 0; i < data.length; i++)
{
var object = data[i];
for (property in object)
{
var value = object[property];
alert(property + "=" + value);
}
}
How can I parse the entire JSON using a single method instead of parsing the JSON array separately?
如何使用单一方法解析整个 JSON 而不是单独解析 JSON 数组?
采纳答案by Amberlamps
Try this:
试试这个:
for(var key in data) {
if(typeof data[key] === "object") {
for(var i = 0; i < data[key].length; i++) {
for(var property in data[key][i]) {
alert(property + " = " + data[key][i][property]);
}
}
} else if(typeof data[key] === "string") {
alert(key + " = " + data[key]);
}
}
回答by Oleg V. Volkov
If your data is a JSON string, you need to decode it to object first. Use JSON.parse
.
如果您的数据是 JSON 字符串,则需要先将其解码为对象。使用JSON.parse
.
回答by Carlos Garcia
I was able to access each value on my multilevel array:
我能够访问我的多级数组上的每个值:
{"dirArray":[{"Dir":{"name":"hr12325","dir_description":"B2B NFIB Field","id":"249"}},{"Dir":{"name":"klk","dir_description":"B2B NFIB klk","id":"251"}}]}
using
使用
data.dirArray[0].Dir.name
data.dirArray[0].Dir.dir_description
as explained here.
为解释在这里。