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

  • 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 `dict`s, sometimes a single `dict`) obtained by decoding a JSON string (with ie `json.loads()`). – bruno desthuilliers Nov 23 '15 at 13:12

2 Answers2

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'}]
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
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'}
GrvTyagi
  • 4,231
  • 1
  • 33
  • 40