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

2

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Is there a way not to replace the duplicate keys?
using the reversed list will give you that - a[::-1] (its just replacing from the end to start :) )
how do i use the reversed list, should i use it as for small_dict in -a:
@TonyRoczz - for small_dict in a[::-1]:
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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.