[英]How to merge multiple json in python
I have a list which holds multiple json strings like this 我有一个包含多个json字符串的列表
a = [{"name": "Alex"},{"Age": 25},{"Address": "16, Mount View"}]
I would like to merge these into a single array like this 我想将它们合并成这样的单个数组
a = [{"name": "Alex","Age": 25,"Address": "16, Mount View"}]
I have tried using jsonmerge
but no luck its working fine when using head' and
base` values. 我试过使用
jsonmerge
但是使用head' and
base`值时运气不好。
Can some one give me a hand in this. 有人可以帮我这个忙吗?
I have also gone through a similar question in stack but it shows merge for separate json but not json in a list How to merge two json 我也经历了一个类似的问题在堆栈中,但它显示了合并为单独的json,但列表中没有json 如何合并两个json
First, these are python dicts 首先,这些是python字典
[{"name": "Alex"},{"Age": 25},{"Address": "16, Mount View"}]
you may call json.dumps on them and turn them into "json strings". 您可以在它们上调用json.dumps并将它们转换为“ json字符串”。
2nd, you can use the dict update method 2,可以使用dict更新方法
a = [{"name": "Alex"},{"Age": 25},{"Address": "16, Mount View"}]
d = {}
for small_dict in a:
d.update(small_dict)
print(d) # Yay!
a = [d]
Be warned! 被警告! , if you have duplicate keys they will override each other
,如果您有重复的键,它们将互相覆盖
Also take a look on "ChainMap" 也看看“ ChainMap”
https://docs.python.org/3/library/collections.html#collections.ChainMap https://docs.python.org/3/library/collections.html#collections.ChainMap
To add to the @yoav glazner's answer and if you are on Python 3.3+, you can use ChainMap
: 要添加到@yoav glazner的答案中,如果您使用的是Python 3.3+,则可以使用
ChainMap
:
>>> from collections import ChainMap
>>> a = [{"name": "Alex"},{"Age": 25},{"Address": "16, Mount View"}]
>>> dict(ChainMap(*a))
{'name': 'Alex', 'Age': 25, 'Address': '16, Mount View'}
See more about the ChainMap
use cases here: 在此处查看有关
ChainMap
用例的更多信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.