Convert List of User Defined Objects to JSON in Python

Python – List of User Defined Objects to JSON String

To convert a Python List, with elements of primitive datatypes, to JSON string, we use json.dumps() function and pass the list as argument to it. But, to convert a list of user defined objects, we use list comprehension with json.dumps().

Syntax

The syntax to use json.dumps() function with list comprehension to convert list list_name of user defined objects to JSON string is

import json

json_string = json.dumps([obj.__dict__ for obj in list_name])

Examples

In this example, we will take a Python list with objects of type Student, and convert it to JSON string.

Python Program

import json

class Student:
    def __init__(self, name, id):
        self.name = name
        self.id = id

s1 = Student('Jack', 4)
s2 = Student('Sunil', 6)

myList = [s1, s2]

jsonStr = json.dumps([obj.__dict__ for obj in myList])
print(jsonStr)
Run

Output

[{"name": "Jack", "id": 4}, {"name": "Sunil", "id": 6}]

Summary

In this tutorial of Python Examples, we learned how to convert a Python List of user-defined objects, into a JSON string.