【问题标题】:Convert from Dict to JSON in Python在 Python 中从 Dict 转换为 JSON
【发布时间】:2014-07-04 11:38:20
【问题描述】:

我想用 json.dumps(arg) 在 Python 中构建一个 dict 将转换为以下 JSON 结构:

"{\"type\":\"id\",
\"entries:\":
[[\"a\",91],
[\"b\",65],
[\"c\",26],
[\"d\",25]]}"

这是我目前所拥有的:

json_dict = {'type': str("id"),
            'entries': [['a': "91"], #Error line
                        ['b': "65"],
                        ['c': "26"],
                        ['d': "25"]]}

我在标有#Error 行的行上收到“无效语法”错误。如何在 dict 中表示这种层次结构,并且仍然能够将其转换为所需的 JSON 结构?

【问题讨论】:

    标签: python json


    【解决方案1】:

    Python 列表使用逗号,而不是冒号:

    json_dict = {'type': str("id"),
                'entries': [['a', "91"],  # note the comma after 'a', not a colon
                            ['b', "65"],
                            ['c', "26"],
                            ['d', "25"]]}
    

    使用逗号,这现在是有效的 Python 语法,生成可以序列化为 JSON 的数据结构:

    >>> json_dict = {'type': str("id"),
    ...             'entries': [['a', "91"],
    ...                         ['b', "65"],
    ...                         ['c', "26"],
    ...                         ['d', "25"]]}
    >>> import json
    >>> json.dumps(json_dict)
    '{"type": "id", "entries": [["a", "91"], ["b", "65"], ["c", "26"], ["d", "25"]]}'
    

    【讨论】:

    • 哦!!!语法非常相似,我把它弄混了。这直接解决了它。谢谢!
    猜你喜欢
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    • 2018-01-08
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多