python - 如何将 python 元组列表转换为 json

标签 python json list tuples

我想将元组列表转换为 json,但我的代码有问题,因为我没有得到我所期望的结果。

我知道这个问题已经被问过,但是通过更简单的输入,我无法让它与我的一起工作。

Input list

result = [('a', 'company', '2', 2, 'myError'), 
            ('c', 'company', '5', 7, 'myError'),
            ('b', 'tax', '23', 1, 'myError')]

这是代码:我迭代列表 result 并解开其中的元组并连接元组 e

e = ()
for element in result:
    e = e + ((element[1],
            (('uuid', str(element[0])),
            ('id', element[2]),
            ('error_id', element[3]),
            ('error_msg', element[4]))),)


logging.info(json.dumps(dict(e)))

Actual result

{
    "company": [
        ["id", "a"], 
        ["row", "2"], 
        ["err", 2], 
        ["msg", "myError"]
    ], 
    "tax": [
        ["id", "b"], 
        ["row", "23"], 
        ["err", 1], 
        ["msg", "myError"]
    ]
}

expected result

{
    "company": [
        {
            "id": "a",
            "row": "2",
            "err": 2,
            "msg": "myError"
        },
        {
            "id": "c",
            "row": "5",
            "err": 7,
            "msg": "myError"
        }
    ],
    "tax": [
        {
            "id": "b",
            "row": "23",
            "err": 1,
            "msg": "myError"
        }    
    ]
}

如何获取正确的json?

最佳答案

from collections import defaultdict

e = defaultdict(list)

for element in result:
    e[element[1]].append({'uuid': str(element[0]), 'id': element[2], 
    'error_id': element[3], 'error_msg': element[4]})

dict(e) 将为您提供所需格式的字典。

关于python - 如何将 python 元组列表转换为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36474742/

相关文章:

python - 提取 Blender 原始坐标 (ORCO)

python - 将列表与列表进行比较以获取与我们正在比较的列表最接近匹配的列表

php - 在 MySQL JSON 字段的数组中搜索值 (Laravel/Lumen)

c程序列表访问值段错误

python - 如何访问python列表并将其保存为字符串

python - 如何在同一个表中的同一个模板上显示来自两个不同 Django 模型的实例?

python - tf.argmax() 用于多个索引 Tensorflow

python - 如何使用 FormFields 的 WTForms FieldList?

java - 嵌套对象: Same Parent Object for multiple Child Objects

javascript - 将 JSON 从 angular.js 发送到 node.js