【问题标题】:Converting a json document array to an array of json documents将 json 文档数组转换为 json 文档数组
【发布时间】:2021-03-14 11:54:24
【问题描述】:

我在 JSON 对象文档中有这个数组。 IpAddresses 数组有大约 2000 个元素

{
   "IpAddresses": [
    "18.213.123.130/32",
    "3.217.79.163/32",
    "3.217.93.44/32",
    .
    .
  ] 
}

我想把它改成这样:

[
    {
        "ipAddress" : "18.213.123.130/32"
    },
    {
        "ipAddress" : "3.217.79.163/32"
    },
    {
        "ipAddress" : "3.217.93.44/32"
    },
    .
    .
]

我正在尝试通过在 python 中使用 json 包来做到这一点

myArray = ["18.213.123.130/32",
           "3.217.79.163/32",
           "3.217.93.44/32"
          ]

ip_addresses = {item: "ipAddress" for item in myArray}
json_str_ip_adresses = json.dumps(ip_addresses)
print(repr(json_str_ip_adresses))

但我得到的输出如下:

> python array-json.py
'{"18.213.123.130/32": "ipAddress", "3.217.79.163/32": "ipAddress", "3.217.93.44/32": "ipAddress"}

我在 JSON 文档中获取所有元素,但我想要将 myArray 中的每个元素作为带有“ipAddress”键的 JSON 文档获取,如下所示:

> python array-json.py
'{"ipAddress" : "18.213.123.130/32"}, {"ipAddress":"3.217.79.163/32", {"ipAddress":"3.217.93.44/32"}'

最好的方法是什么?

【问题讨论】:

    标签: python arrays json


    【解决方案1】:

    您可以将列表推导式用作:

    ip_addresses = [{"ipAddress": item} for item in myArray]
    

    另外,您不需要json.dumps()repr() 来回转换。

    【讨论】:

      【解决方案2】:
      data = { "IpAddresses": [ "18.213.123.130/32", "3.217.79.163/32", "3.217.93.44/32" ] }
      [{"ipAddress": i} for i in data["IpAddresses"]]
      

      结果:

      [{'ipAddress': '18.213.123.130/32'},
       {'ipAddress': '3.217.79.163/32'},
       {'ipAddress': '3.217.93.44/32'}]
      

      【讨论】:

        猜你喜欢
        • 2017-06-01
        • 2012-04-14
        • 1970-01-01
        • 1970-01-01
        • 2018-06-01
        • 2020-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多