This concise, example-based article will show you how to convert a list to a JSON-formatted string in Python. No more delay; let’s dive right in!
Using the json.dumps() function (basic)
This approach is simple and straightforward. What you need to do is just pass your list as an argument to the json.dumps()
function to turn it into a JSON string.
Example:
from pprint import pprint
import json
list1 = [1, 2, 3, 'A', 'B', 'C']
list2 = [
[2023, 2024, 2025],
['sling', 'academy', 'python'],
]
json1 = json.dumps(list1)
json2 = json.dumps(list2)
pprint(json1)
pprint(json2)
Output:
'[1, 2, 3, "A", "B", "C"]'
'[[2023, 2024, 2025], ["sling", "academy", "python"]]'
Using the json.JSONEncoder subclass (advanced)
This technique creates a custom subclass of json.JSONEncoder
and override its default()
method to handle the serialization of the list. It requires you to write more code but gives you more control over serialization options.
The example below demonstrates the benefit of this approach when converting a list of class instances to JSON:
import json
# Define Person class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Define custom encoder
class PersonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Person):
return {
'name': obj.name,
'age': obj.age,
'type': 'Person'
}
return super().default(obj)
# Create a list of Person objects
person_list = [
Person('Wolf', 35),
Person('Ranni the Witch', 300),
Person('Geralt of Rivia', 999)
]
# Convert the list to JSON using the custom encoder
json_data = json.dumps(person_list, cls=PersonEncoder, indent=2)
print(json_data)
Output:
[
{
"name": "Wolf",
"age": 35,
"type": "Person"
},
{
"name": "Ranni the Witch",
"age": 300,
"type": "Person"
},
{
"name": "Geralt of Rivia",
"age": 999,
"type": "Person"
}
]
In this example, we have a Person
class representing individuals with a name
and age
. By creating a custom PersonEncoder
subclass, we can define how Person
objects should be serialized to JSON. In the default()
method, we check if the object is an instance of Person
and return a dictionary representation with additional metadata (type
). This allows us to have custom serialization logic specifically for Person
objects.