Python 如何合并两个JSON
我有两个这样的格言:Python 如何合并两个JSON,python,json,list,dictionary,Python,Json,List,Dictionary,我有两个这样的格言: array1=["1","2"] array=[ [{"a":"1"},{"b":"2"}], [{"c":"1"},{"d":"2"}] ] json3=[ "1": [{a:"1"},{b:"2"}], "2": [{c:"1"},{d:"2"}] ] 我想将它们转换为JSON,然后像这样合并它们: array1=["1","2"] array=[ [{"a":"
array1=["1","2"]
array=[
[{"a":"1"},{"b":"2"}],
[{"c":"1"},{"d":"2"}]
]
json3=[
"1": [{a:"1"},{b:"2"}],
"2": [{c:"1"},{d:"2"}]
]
我想将它们转换为JSON,然后像这样合并它们:
array1=["1","2"]
array=[
[{"a":"1"},{"b":"2"}],
[{"c":"1"},{"d":"2"}]
]
json3=[
"1": [{a:"1"},{b:"2"}],
"2": [{c:"1"},{d:"2"}]
]
我已经通过JSON.dumps()
将它们转换为JSON,现在我不知道如何以我想要的方式合并它们
我的问题在某种程度上类似于,但结果不同
我试过这个:
json3 = {key: value for (key, value) in (json1.items() + json2.items())}
但我得到:
'str' object has no attribute 'items'
我尝试了一些其他的方法,但没有一种能达到我想要的效果
dict_of_dicts = {i:d for i, d in zip(idJson, imgJson)} # Also didn't work
你可以用图书馆来做这件事
json.load
将json字符串转换为dict。json.dumps
从dict恢复json
json1='["1","2"]'
json2='[[{"a":"1"},{"b":"2"}],[{"c":"1"},{"d":"2"}]]'
import json
j1 = json.loads(json1)
j2 = json.loads(json2)
j3 = dict(zip(j1, j2))
json3 = json.dumps(j3)
输出将是
>>> json3
'{"1": [{"a": "1"}, {"b": "2"}], "2": [{"c": "1"}, {"d": "2"}]}'
你需要
json.loads
@PadraicCunningham和json.dumps
为什么你发布的东西看起来像python列表,而它们是字符串?想编辑吗?@BhargavRao,除非他们再次需要字符串;)@AlexJolig,你不能有你想要的格式,你可以有一个dict或一个列表,而不是两者的混合。你在用json做什么?