k4ppa k4ppa - 23 days ago 12
JSON Question

How to turn a python list of tuples into a json

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

This question it's been already asked, I know, but with much simplier input and I can't make it work with my 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?

Answer
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 dict in the desired format.

Comments