我有一个元组列表,并希望从中创建JSON
[(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')]
预期的JSON
{
"List": [
{
"name": "1",
"description": "a",
"type": "A"
},
{
"name": "2",
"description": "b",
"type": "B"
},
{
"name": "3",
"description": "c",
"type": "C"
},
and so on....
]
}
我该怎么做?
重复的已确定答案无效并发出此错误
ValueError: dictionary update sequence element #0 has length 3; 2 is required
答案 0 :(得分:2)
zip
键和每个元组在结果上调用dict然后 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]})
这给了你:
'{"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"}]}'