I have a list which holds multiple json strings like this
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.
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
First, these are python dicts
[{"name": "Alex"},{"Age": 25},{"Address": "16, Mount View"}]
you may call json.dumps on them and turn them into "json strings".
2nd, you can use the dict update method
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"
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
:
>>> 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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.