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
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'}]
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'}
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
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'}]
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'}