Contents
Convert Dataclass to JSON in Python
In this tutorial, you will learn how to convert a dataclass instance object to a JSON string in Python.
To convert a given dataclass object into a JSON string, follow these steps.
- Given an instance of a dataclass.
- Pass the dataclass instance as argument to dataclasses.asdict() function. The function returns the dictionary representation of the given dataclass instance.
- Convert this dictionary into a JSON string using json.dumps().
Examples
1. Convert a simple dataclass instance to JSON string
In this example, we’ll create a dataclass to represent a Person with name and age attributes.
We shall create an instance of this dataclass person_1, get the dictionary representation of this instance using dataclasses.asdict() method, and then pass this dictionary as argument to json.dumps() method.
Python Program
import dataclasses
import json
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
# Create an instance of dataclass Person
person_1 = Person("Ram", 21)
# Convert dataclass to dictionary
person_1_dict = dataclasses.asdict(person_1)
# Convert dictionary to JSON string
person_1_json = json.dumps(person_1_dict)
print(f"JSON String\n{person_1_json}")
Run Code CopyOutput
JSON String
{"name": "Ram", "age": 21
2. Convert nested dataclass instance to JSON string
In this example, we’ll define two dataclasses: Person and Student. Student dataclass consists of the instance of Person dataclass as an attribute.
We shall create an instance of Student dataclass, student_1, and convert this instance into a JSON string.
Python Program
import dataclasses
import json
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
@dataclass
class Student():
student_id: str
basic_details: Person
# Create an instance of dataclass Person
student_1 = Student("12345", Person("Ram", 21))
# Convert dataclass to dictionary
student_1_dict = dataclasses.asdict(student_1)
# Convert dictionary to JSON string
student_1_json = json.dumps(student_1_dict)
print(f"JSON String\n{student_1_json}")
Run Code CopyOutput
{"student_id": "12345", "basic_details": {"name": "Ram", "age": 21}}
Summary
In this Python dataclasses tutorial, we learned how to convert a given dataclass instance into a JSON string.