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

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types