Fix Python – Python: converting a list of dictionaries to json

Question

Asked By – Apoorv Ashutosh

I have a list of dictionaries, looking some thing like this:

list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]

and so on. There may be more documents in the list. I need to convert these to one JSON document, that can be returned via bottle, and I cannot understand how to do this. Please help. I saw similar questions on this website, but I couldn’t understand the solutions there.

Now we will see solution for issue: Python: converting a list of dictionaries to json


Answer

use json library

import json
json.dumps(list)

by the way, you might consider changing variable list to another name, list is the builtin function for a list creation, you may get some unexpected behaviours or some buggy code if you don’t change the variable name.

This question is answered By – markcial

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0