109

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.

user2314737
  • 24,359
  • 17
  • 91
  • 104
Apoorv Ashutosh
  • 3,406
  • 7
  • 21
  • 24

4 Answers4

162

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.

markcial
  • 8,713
  • 4
  • 30
  • 41
54
import json

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

Write to json File:

with open('/home/ubuntu/test.json', 'w') as fout:
    json.dump(list , fout)

Read Json file:

with open(r"/home/ubuntu/test.json", "r") as read_file:
    data = json.load(read_file)
print(data)
#list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]
snakecharmerb
  • 36,887
  • 10
  • 71
  • 115
Ramineni Ravi Teja
  • 2,967
  • 22
  • 32
1
response_json = ("{ \"response_json\":" + str(list_of_dict)+ "}").replace("\'","\"")
response_json = json.dumps(response_json)
response_json = json.loads(response_json)
Akhilesh Joshi
  • 220
  • 3
  • 10
  • 4
    Hi! While this may solve OP's problem, it is generally discouraged to write code only answers on SO. Please provide some explanation as to why this is a solution to the problem as it will help OP better understand and will benefit future visitors of the site. Thanks! – d_kennetz Apr 10 '19 at 22:18
0

To convert it to a single dictionary with some decided keys value, you can use the code below.

data = ListOfDict.copy()
PrecedingText = "Obs_"
ListOfDictAsDict = {}
for i in range(len(data)):
    ListOfDictAsDict[PrecedingText + str(i)] = data[i]