Mastering JSON Serialization With Pydantic
'Mastering JSON Serialization with Pydantic' guides you to seamlessly transform data between Python objects and JSON representations.
Join the DZone community and get the full member experience.
Join For FreePydantic comes with inherent capabilities for JSON Serialization, making the process of converting Pydantic models to JSON and back straightforward.
Serializing Models to JSON:
In Pydantic, converting a model to JSON involves utilizing the JSON () method in an instance of the model.
from pydantic import BaseModel
from typing import Optional
class User(BaseModel):
id: int
name: str
age: int
dept: Optional[str]
user = User(id=1, name="Test user", age = 12, dept="Information Technology")
user.json()
The JSON () method will return the string representation of the model data, which is
{"id":1,"name":"Test user","age":12,"dept":"Information Technology"}
The model instance also has a method dict()
that returns the Python dictionary object.
model = user.dict()
model['name'] // Test user
Customizing JSON Output:
The JSON () method offers flexibility in customizing the output by allowing the exclusion of specific fields during serialization.
user_json = user.json(exclude={"age"})
user_json //{"id":1,"name":"Test user","dept":"Information Technology"}
The JSON (by_alias=True) parameter in Pydantic's JSON () method is used to instruct Pydantic to consider the alias names of the fields while generating the JSON output. By default, Pedantic uses the original attribute names defined in the model for JSON serialization.
Enums in JSON Serialization:
Enums are a way to represent a set of named values, and Pydantic allows the use of Enum types within its models. Pedantic automatically converts the Enum value to its corresponding string representation during JSON serialization.
from enum import Enum
class Department(str, Enum):
it = "Information Technology"
hr = "Humar Resource"
acct = "Accounts"
user = User(id=1, name="Test user", age = 12, dept=Department.it)
user.json() //{"id":1,"name":"Test user","age":12,"dept":"Information Technology"}
JSON to Model:
To translate JSON into a Pydantic model, Pydantic offers two methods: 'parse_obj' and 'parse_raw'.
Parse_obj:
It takes a dictionary as input. Parses the dictionary against the model's field definitions, performing type conversion, applying defaults, and running validators. The ideal use case for using 'parse_obj' is when you already have the data in a dictionary format, such as from a request body or database query.
json = {"id":1,"name":"Test user","age":12, "dept":"Information Technology"}
User.parse_obj(json)
// User(id=1, name='Test user', age=12, dept='Information Technology')
Parse_raw:
It inputs a string or bytes object (typically JSON data). It’s useful when you have raw data, such as a JSON string from an API response or file.
user_json = '{"id":1,"name":"Test user","age":12,"dept":"Information Technology"}'
User.parse_raw(user)
// User(id=1, name='Test user', age=12, dept='Information Technology')
parse_obj
is generally considered more efficient thanparse_raw
as it avoids the decoding step.parse_raw
is deprecated in Pydantic v2, but still available for backward compatibility.- Both methods raise
ValidationError
if data is invalid or doesn't match the model's expectations.
Opinions expressed by DZone contributors are their own.
Comments