【发布时间】:2022-01-21 10:42:07
【问题描述】:
我尝试从 python 字典创建 JSON 的和平。不幸的是,我还不能得到正确的格式。我的 json 对象“类型”中需要一个数组。我该如何解决这个问题?
我的代码:
import json
association_item = {}
association_item['types']={}
association_item['types']['associationCategory'] = 'A'
association_item['types']['associationTypeId'] = '4'
我的听写:
{'types': {'associationCategory': 'A', 'associationTypeId': '4'}}
我的 JSON:
{
"types": {
"associationCategory": "A",
"associationTypeId": "4"
}
}
我想要什么:
{
"types": [{
"associationCategory": "A",
"associationTypeId": "4"
}]
}
【问题讨论】:
-
我不明白您为什么希望将字典值作为对象的 array 输出。如果这是您想要的,您需要更改外部字典以包含字典的 list 而不仅仅是字典。您基本上可以在 Python 中编写与要输出的 JSON 相同的内容,因为 Python 可以在字符串上使用单个 或 双引号。