2

这是我需要解析的 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"}]}

我已经尝试并实现了这里提供的解决方案,这是在解决方案中定义的 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);
     }
 }

外部 JSON数据是从服务器返回的,是的,我尝试使用以下代码进行解析,但没有结果:

for (var i = 0; i < data.length; i++) 
{
 var object = data[i];
 for (property in object) 
 {
    var value = object[property];
    alert(property + "=" + value);
 }
}

如何使用单一方法解析整个 JSON,而不是单独解析 JSON 数组?

4

3 回答 3

3

试试这个:

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]);
    }
}
于 2012-06-04T12:44:44.310 回答
1

如果您的数据是 JSON 字符串,则需要先将其解码为对象。使用JSON.parse.

于 2012-06-04T12:46:47.743 回答
0

我能够访问我的多级数组上的每个值:

{"dirArray":[{"Dir":{"name":"hr12325","dir_description":"B2B NFIB Field","id":"249"}},{"Dir":{"name":"klk","dir_description":"B2B NFIB klk","id":"251"}}]}

使用

data.dirArray[0].Dir.name
data.dirArray[0].Dir.dir_description

如此所述。

于 2012-10-01T20:53:58.587 回答