126

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
  • 27,088
  • 20
  • 102
  • 114
Apoorv Ashutosh
  • 3,834
  • 7
  • 23
  • 24

4 Answers4

172

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
  • 9,041
  • 4
  • 31
  • 41
62
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
  • 47,570
  • 11
  • 100
  • 153
Ramineni Ravi Teja
  • 3,568
  • 26
  • 37
1
response_json = ("{ \"response_json\":" + str(list_of_dict)+ "}").replace("\'","\"")
response_json = json.dumps(response_json)
response_json = json.loads(response_json)
Akhilesh Joshi
  • 288
  • 3
  • 13
  • 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]