简体   繁体   中英

How to turn a python list of tuples into a json

I want to turn a list of tuples into json, but something is wrong with my code, because I don't get what I expect.

This question has been already asked, I know, but with simpler input and I can't make it work with mine.

Input list

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

This is the code: I iterate over the list result and unwrap the tuples inside it and concatenate the tuple 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"
        }    
    ]
}

How can I obtain the correct 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) will give you a dictionary in the desired format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM