How to convert list of dict to json in python?

Viewed 1462

I have a list of JSON and I want to convert then into single JSON, I tried with json.dumps, but that still gives a list of JSON as the result.

"response":[{"sent":46},{"drafts":2},{"completed":48},{"pending":1}]

I want it in the form of

"response":{"sent":46,"drafts":2,"completed":48,"pending":1}

Can you please help me with this?

2 Answers

you can use:

from itertools import chain
r = {"response" :[{"sent":46},{"drafts":2},{"completed":48},{"pending":1}]}


r['response'] = dict(chain(*map(dict.items, r['response'])))
# same with:
# r['response'] = dict(chain.from_iterable(map(dict.items, r['response'])))
r

output:

{'response': {'sent': 46, 'drafts': 2, 'completed': 48, 'pending': 1}}

or you can use a dictionary comprehension:

r['response'] = {k: v for d in r['response'] for k, v in d.items()}

output:

{'response': {'sent': 46, 'drafts': 2, 'completed': 48, 'pending': 1}}

you can use

json_obj = {"response":[{"sent":46},{"drafts":2},{"completed":48},{"pending":1}]}
{k: {list(i.keys())[0]: list(i.values())[0] for i in v} for k, v in json_obj.items()}

that will output

{'response': {'sent': 46, 'drafts': 2, 'completed': 48, 'pending': 1}}
Related