【问题标题】:Script that stores multiple values from JSON dictionary into array将 JSON 字典中的多个值存储到数组中的脚本
【发布时间】:2019-02-10 14:56:06
【问题描述】:

在收到 API 请求后,我有超过 1000 个 JSON 格式的字典。如何创建一个遍历所有字典并存储一个键值对的值的脚本?

例子

},"testData"
{
    "testJSON": "test",
    "phone": null,
    "address: "122 main st"
}, "testData1"
{
    "testJSON": "test1",
    "phone": null,
    "address: "123 main st"
},

例如,如何获取每个 JSON 字典的“地址”字段?

【问题讨论】:

  • 它是“一个键值对”还是“每一个 JSON 字典”?此外,您的 JSON 示例格式不正确。是 JSON 字典列表吗?
  • @DeveshKumarSingh 是的,它是一个 json 字典列表

标签: javascript python arrays json


【解决方案1】:

你需要先解析你的json,像这样:

var json = JSON.parse(jsonString);

然后你可以迭代你的 json 键并对根值做一些事情,比如:

for(var el in json)
{
    console.log(json[el]) // will log every root element
    console.log(json[el].phone) // will log phone of each element
}

小提琴示例:https://jsfiddle.net/1ky6dzen/

【讨论】:

    【解决方案2】:

    在python中可以这样完成:

    data = [{
        "testJSON": "test",
        "phone": null,
        "address: "122 main st"
    }, "testData1"
    {
        "testJSON": "test1",
        "phone": null,
        "address: "123 main st"
    }]
    
    my_array = []
    
    for obj in data:
        my_array.append(obj['address'])
    
    print(my_array)
    

    希望这就是你所追求的 :)

    【讨论】:

      【解决方案3】:

      使用 forEach 循环遍历对象的键

      var a={"testData":
      {
          "testJSON": "test",
          "phone": null,
          "address": "122 main st"
      }, "testData1":
      {
          "testJSON": "test1",
          "phone": null,
          "address": "123 main st"
      }};
      Object.keys(a).forEach(e=>console.log(a[e].address))

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-24
        • 1970-01-01
        • 1970-01-01
        • 2016-02-05
        • 2019-08-12
        • 2019-10-23
        • 1970-01-01
        相关资源
        最近更新 更多