Prashant Prashant - 5 months ago 12
JSON Question

Create a JSON dict from a list of values from a tuple and a separate list of keys

I have a list of tuple and want to make JSON from it

[(1, 'a', 'A'), (2, 'b', 'B'), (3, 'c', 'C'), (4, 'd', 'D'), (5, 'e', 'E'), (6, 'f', 'F'), (7, 'g', 'G'), (8, 'h', 'H'), (9, 'i', 'I')]


And Expected JSON

{
"List": [
{
"name": "1",
"description": "a",
"type": "A"
},
{
"name": "2",
"description": "b",
"type": "B"
},
{
"name": "3",
"description": "c",
"type": "C"
},
and so on....
]
}


How can i do that?

The duplicate identified answers didn't work and gave this error

ValueError: dictionary update sequence element #0 has length 3; 2 is required

Answer

zip the keys and each tuple calling dict on the result then json.dumps:

import json
keys = ["name", "description","type"]

l=[(1, 'a', 'A'), (2, 'b', 'B'), (3, 'c', 'C'), (4, 'd', 'D'), (5, 'e', 'E'), (6, 'f', 'F'), (7, 'g', 'G'), (8, 'h', 'H'), (9, 'i', 'I')]


js =  json.dumps({"List":[dict(zip(keys, tup)) for tup in l]})

Which gives you:

'{"List": [{"type": "A", "name": 1, "description": "a"}, {"type": "B", "name": 2, "description": "b"}, {"type": "C", "name": 3, "description": "c"}, {"type": "D", "name": 4, "description": "d"}, {"type": "E", "name": 5, "description": "e"}, {"type": "F", "name": 6, "description": "f"}, {"type": "G", "name": 7, "description": "g"}, {"type": "H", "name": 8, "description": "h"}, {"type": "I", "name": 9, "description": "i"}]}'
Comments