【发布时间】: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"}'
最好的方法是什么?
【问题讨论】: