Convert Array of Dictionaries to JSON in Python
In this tutorial, you’ll learn various methods to convert an array of dictionaries to JSON.
We’ll start with basic methods using the json
module and progress to more advanced techniques involving Pandas and list comprehension.
Using json.dumps
The json.dumps
method serializes your Python object into a JSON formatted string.
First, you’ll need to import the json
module:
import json
Now, consider the following sample data:
data = [ {"customer_id": 101, "name": "Jordan", "plan": "Premium", "balance": 45.50}, {"customer_id": 102, "name": "Taylor", "plan": "Basic", "balance": 15.75}, {"customer_id": 103, "name": "Alex", "plan": "Standard", "balance": 30.00} ]
To convert this array of dictionaries to a JSON string, you can use json.dumps
:
json_data = json.dumps(data) print(json_data)
Output:
[{"customer_id": 101, "name": "Jordan", "plan": "Premium", "balance": 45.5}, {"customer_id": 102, "name": "Taylor", "plan": "Basic", "balance": 15.75}, {"customer_id": 103, "name": "Alex", "plan": "Standard", "balance": 30.0}]
This output shows your data array transformed into a JSON-formatted string.
Each dictionary in the array becomes a JSON object, and the entire array is enclosed in square brackets, following the JSON array format.
Using json.dump
While json.dumps
is excellent for converting data to a JSON string, json.dump
allows you to write JSON data directly to a file.
Let’s say you want to save the customer data array to a JSON file. Here’s how you do it:
Recall the sample data:
data = [ {"customer_id": 101, "name": "Jordan", "plan": "Premium", "balance": 45.50}, {"customer_id": 102, "name": "Taylor", "plan": "Basic", "balance": 15.75}, {"customer_id": 103, "name": "Alex", "plan": "Standard", "balance": 30.00} ]
To write this data to a file in JSON format, you can use json.dump
:
with open('customers.json', 'w') as file: json.dump(data, file)
After executing this code, a file named customers.json
will be created in your working directory.
The use of the with
statement ensures that the file is properly closed after the write operation, which is a best practice in file handling.
Using Pandas
First, import the Pandas library:
import pandas as pd
We’ll use the same sample data:
data = [ {"customer_id": 101, "name": "Jordan", "plan": "Premium", "balance": 45.50}, {"customer_id": 102, "name": "Taylor", "plan": "Basic", "balance": 15.75}, {"customer_id": 103, "name": "Alex", "plan": "Standard", "balance": 30.00} ]
To convert this data into a JSON string with Pandas, start by creating a DataFrame from the array of dictionaries:
df = pd.DataFrame(data)
Then, convert the DataFrame to a JSON string:
json_data = df.to_json(orient='records') print(json_data)
Output:
[{"customer_id":101,"name":"Jordan","plan":"Premium","balance":45.5},{"customer_id":102,"name":"Taylor","plan":"Basic","balance":15.75},{"customer_id":103,"name":"Alex","plan":"Standard","balance":30.0}]
You can filter, sort, or apply other operations before conversion.
The to_json
method with the records
orientation produces a list of records, which is a common format for JSON data.
Using List Comprehension
List comprehension in Python provides a concise way to create lists. It can also be used innovatively for converting arrays of dictionaries into JSON format.
This method is particularly useful when you need to preprocess each dictionary in the array before converting it to JSON.
Let’s continue using our example from the telecom company:
First, remember to import the json
module:
import json
Here’s our sample data again:
data = [ {"customer_id": 101, "name": "Jordan", "plan": "Premium", "balance": 45.50}, {"customer_id": 102, "name": "Taylor", "plan": "Basic", "balance": 15.75}, {"customer_id": 103, "name": "Alex", "plan": "Standard", "balance": 30.00} ]
To convert this data to JSON using list comprehension, you might want to preprocess the data. For example, let’s say you want to round the balance to 2 decimal places in each dictionary:
You can use list comprehension to process the data:
processed_data = [{key: round(value, 2) if isinstance(value, float) else value for key, value in customer.items()} for customer in data]
Then you can convert the processed data to a JSON string:
json_data = json.dumps(processed_data) print(json_data)
Output:
[{"customer_id": 101, "name": "Jordan", "plan": "Premium", "balance": 45.5}, {"customer_id": 102, "name": "Taylor", "plan": "Basic", "balance": 15.75}, {"customer_id": 103, "name": "Alex", "plan": "Standard", "balance": 30.0}]
In this method, the list comprehension first processes each dictionary in the array (e.g., rounding off float values) and then the json.dumps
method is used to convert the processed array into a JSON string.
Serializing Custom Objects
JSON format does not directly support Python’s custom object serialization.
However, with a bit of extra coding, you can serialize these objects into JSON.
Let’s assume you have a custom class representing customers and you want to serialize it:
First, define the custom class:
class Customer: def __init__(self, customer_id, name, plan, balance): self.customer_id = customer_id self.name = name self.plan = plan self.balance = balance def serialize(self): return { "customer_id": self.customer_id, "name": self.name, "plan": self.plan, "balance": self.balance }
Let’s create a list of customer objects:
customers = [ Customer(101, "Jordan", "Premium", 45.50), Customer(102, "Taylor", "Basic", 15.75), Customer(103, "Alex", "Standard", 30.00) ]
To serialize these custom objects to JSON, you’ll need to convert each object to a dictionary using serialize
method in the Customer
class and then use json.dumps
:
import json serialized_data = [customer.serialize() for customer in customers] json_data = json.dumps(serialized_data) print(json_data)
Output:
[{"customer_id": 101, "name": "Jordan", "plan": "Premium", "balance": 45.5}, {"customer_id": 102, "name": "Taylor", "plan": "Basic", "balance": 15.75}, {"customer_id": 103, "name": "Alex", "plan": "Standard", "balance": 30.0}]
In this method, the serialize
function of each Customer
instance converts the object’s attributes to a dictionary.
This collection of dictionaries is then turned into a JSON string using json.dumps
.
Mokhtar is the founder of LikeGeeks.com. He is a seasoned technologist and accomplished author, with expertise in Linux system administration and Python development. Since 2010, Mokhtar has built an impressive career, transitioning from system administration to Python development in 2015. His work spans large corporations to freelance clients around the globe. Alongside his technical work, Mokhtar has authored some insightful books in his field. Known for his innovative solutions, meticulous attention to detail, and high-quality work, Mokhtar continually seeks new challenges within the dynamic field of technology.