我如何使用Python将2 json合并为1

时间:2019-05-11 11:57:37

标签: python

我刚刚开始学习Python和Json。请放轻松我

我有这样的东西

o = [{ "name" : "MrA", "Age" : 33 },
     { "name" : "MrB", "Age": 34 }]
p = [{ "place" : "London", "Year" : 2018}, 
     {"place" : "NewYork", "Year":2017}]

所以我想做的就是将它们结合起来并给它们起这样的名字

[
 {"person": [{ "name" : "MrA", "Age" : 33 },
             { "name" : "MrB", "Age": 34 }],
  "cities": [{ "place" : "London", "Year" : 2018},
             {"place" : "NewYork", "Year":2017}]
]

1 个答案:

答案 0 :(得分:1)

2个对象o和p是字典,而不是json。 但是,您可以尝试使用这种方法来获取json对象。

import json

o = [{ "name" : "MrA", "Age" : 33 },
     { "name" : "MrB", "Age": 34 }]
p = [{ "place" : "London", "Year" : 2018}, 
     {"place" : "NewYork", "Year":2017}]

output = {"persons": o, "cities": p}
output = json.dumps(output)
print(output)