【问题标题】:Create json from python dict从 python dict 创建 json
【发布时间】: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 可以在字符串上使用单个 双引号。

标签: python json


【解决方案1】:

你需要正确添加,比如

association_item['types'] = 
    [ { 'associationCategory': 'A',
        'associationTypeId': '4' } ]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    相关资源
    最近更新 更多