How to merge multiple json objects into a single json object using python

Question:

I have a list which contains multiple JSON objects and I would like to combine those JSON objects into a single json object, I tried using jsonmerge but with no luck.

My list is:

t = [{'ComSMS': 'true'}, {'ComMail': 'true'}, {'PName': 'riyaas'}, {'phone': '1'}]

The desired output is

t = [{'ComSMS': 'true', 'ComMail': 'true', 'PName': 'riyaas', 'phone': '1'}]

I put the list in a for loop and tried json merge and I got the error head missing expected 2 arguments got 1

Can someone help me solve this issue

Asked By: user5189062

||

Answers:

You may do like this but it should not be in order.

>>> t = [{'ComSMS': 'true'}, {'ComMail': 'true'}, {'PName': 'riyaas'}, {'phone': '1'}]
>>> [{i:j for x in t for i,j in x.items()}]
[{'ComSMS': 'true', 'phone': '1', 'PName': 'riyaas', 'ComMail': 'true'}]
Answered By: Avinash Raj

Loop on your list of dict. and update an empty dictionary z in this case.

z.update(i): Get K:V from i(type : dict.) and add it in z.

t = [{'ComSMS': 'true'}, {'ComMail': 'true'}, {'PName': 'riyaas'}, {'phone': '1'}]
z = {}
In [13]: for i in t:
             z.update(i)
   ....:     

In [14]: z
Out[14]: {'ComMail': 'true', 'ComSMS': 'true', 'PName': 'riyaas', 'phone': '1'}
Answered By: GrvTyagi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.