Sling Academy
Home/Python/Python: How to Convert a List to JSON (2 Approaches)

Python: How to Convert a List to JSON (2 Approaches)

Last updated: June 19, 2023

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.

Next Article: Python: 3 Ways to Fetch Data from GitHub API

Previous Article: Python: Write a list of dictionaries to a JSON file

Series: Python: Network & JSON tutorials

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots