Python: converting a list of dictionaries to json
use json library
import jsonjson.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.
import jsonlist = [{'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]}]
response_json = ("{ \"response_json\":" + str(list_of_dict)+ "}").replace("\'","\"")response_json = json.dumps(response_json)response_json = json.loads(response_json)