51

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

1
  • 6
    There's no such thing as a "JSON object" in Python - you either have a Python string containing JSON (which is a text format...) or a Python object (usually a list of dicts, sometimes a single dict) obtained by decoding a JSON string (with ie json.loads()). Commented Nov 23, 2015 at 13:12

2 Answers 2

20

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'}]
1
  • JSON specs cleary states that "objects" are an unordered collection of key:value pairs, so no one should rely on ordering of keys anyway. Commented Nov 23, 2015 at 13:14
4

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'}
1
  • Please explain your answers. Commented Nov 23, 2015 at 14:33