Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: converting a list of dictionaries to json

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.

like image 583
Apoorv Ashutosh Avatar asked Feb 03 '14 10:02

Apoorv Ashutosh


People also ask

Can JSON be a list of dictionaries?

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.

How do I dump a dictionary in JSON?

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.

Can we convert dictionary to JSON in Python?

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.

How do you convert a list to a JSON object in Python?

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.


2 Answers

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.

like image 89
markcial Avatar answered Sep 30 '22 14:09

markcial


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]}] 
like image 30
Ramineni Ravi Teja Avatar answered Sep 30 '22 12:09

Ramineni Ravi Teja