【问题标题】:Parsing nested JSON without using getJSON()不使用 getJSON() 解析嵌套 JSON
【发布时间】:2013-08-20 17:45:25
【问题描述】:

我知道已经有一百个“解析 json”问题 - 但我找不到与我自己的情况相匹配的解决方案。

我收到与此类似的 JSON:

{    
"parent:array": [
    {
        "child:value": "test1",
        "child:array": [
            {
                "child:subvalue": "test3"
            }
        ]
    },
    {
        "child:value": "test2",
        "child:array": [
            {
                "child:subvalue": "test4"
            }
        ]
    }
]
}

我可以通过执行以下操作访问child:value(其中response 是JSON):

var parameters = response['parent:array'];
$.each(parameters, function (idx, data) {
    var childValue = data['child:value'];
});

但是,我还无法检索到child:subvalue。可以作为each 的一部分完成吗?

我尝试了以下方法但没有成功:

response['parent:array']['child:array']

还有……

var childSubvalue = data['child:array']['child:subvalue'];

【问题讨论】:

  • 您的 JSON 无效。 "child:array" 有一个关闭 } 应该有一个关闭 ]
  • 你试过了吗:"child:array.child:subvalue"
  • @blurfus:你需要使用[],因为:
  • @RocketHazmat 打错了,谢谢指正。
  • 您的 json 仍然无效。 “test3”后面的逗号需要去掉。

标签: jquery json parsing


【解决方案1】:

"child:array" 是一个数组,所以你需要给一个索引来选择,像这样:

var childSubvalue = data['child:array'][0]['child:subvalue'];

【讨论】:

  • 谢谢西蒙。您知道如何将其合并到循环中吗? [0] 将是 [i] 在哪里?例如,我可以将该行添加到我在问题中定义的each - 但我只会得到第一个child:subvalue,因为parent:array 的大小为“1”。
  • 是的,只需在循环中添加另一个循环。
【解决方案2】:

一旦你的 json 有效:

$.each(parameters, function (idx, data) {
    var childValue = data['child:value'], childArray = data['child:array'];
    $.each(childArray, function(i, d) {
        alert(d['child:subvalue']);
    });
});

Fiddle

【讨论】:

  • 完美——正是我想要的。谢谢。
【解决方案3】:

使用 array.forEach 遍历外部和内部数组;

var json = {    
"parent:array": [
    {
        "child:value": "test1",
        "child:array": [
            {
                "child:subvalue": "test3",
            }
        ]
    },
    {
        "child:value": "test2",
        "child:array": [
            {
                "child:subvalue": "test4"
            }
        ]
    }
]
}

json["parent:array"].forEach(function(parent) {
    console.log(parent["child:value"]);
    parent["child:array"].forEach(function(child) {
        console.log(child["child:subvalue"]);
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-20
    • 2015-08-28
    • 2017-08-03
    • 2018-10-06
    • 1970-01-01
    相关资源
    最近更新 更多