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.
A “JSON array” is very similar to a Python list. In the same way that JSON objects can be nested within arrays or arrays nested within objects, Python dictionaries can be nested within lists or lists nested within dictionaries. So pretty much any JSON data structure can be translated into a complex Python data object.
You can convert a dictionary to a JSON string using the json. dumps() method. The process of encoding the JSON is usually called serialization. That term refers to transforming data into a series of bytes (hence serial) stored or transmitted across the network.
Python possesses a default module, 'json,' with an in-built function named dumps() to convert the dictionary into a JSON object by importing the "json" module. "json" module makes it easy to parse the JSON strings which contain the JSON object.
To convert a list to json in Python, use the json. dumps() method. The json. dumps() is a built-in function that takes a list as an argument and returns the json value.
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.
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]}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With