2

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' andbase` 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

Community
  • 1
  • 1
Tony Roczz
  • 2,366
  • 6
  • 32
  • 59
  • Possible duplicate of [How do I merge a list of dicts into a single dict?](http://stackoverflow.com/questions/3494906/how-do-i-merge-a-list-of-dicts-into-a-single-dict) – taleinat Jan 13 '16 at 05:35
  • This has nothing to to with JSON, since at this point you simply have a list of Python dictionary objects. There are already many answers on how to merge a list of dicts together, e.g. [the answers to this SO question](http://stackoverflow.com/questions/3494906/how-do-i-merge-a-list-of-dicts-into-a-single-dict). – taleinat Jan 13 '16 at 05:37

2 Answers2

3

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

Yoav Glazner
  • 7,936
  • 1
  • 19
  • 36
2

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:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195