Simplifying Data Serialization with Pydantic, `.dict()` and `.json()`


When working with data models in Python, Pydantic is a fantastic library that streamlines validation and serialization. One of its most powerful features is the ease with which you can convert Pydantic classes into JSON format. In this blog post, we’ll explore how to achieve this using the .dict() and .json() methods, understand their differences, and see how to exclude null keys from the output.

Easy JSON Conversion with Pydantic

Pydantic allows you to define data models using Python classes, which can then be effortlessly converted to JSON format. This can be particularly useful when building APIs or working with data interchange formats. To convert a Pydantic class to JSON, you can use either the .dict() or .json() methods. Here’s a quick example to illustrate:

from pydantic import BaseModel

class User(BaseModel:
id: int
name: str
email: str = None

user = User(id=1, name="Alice")

To convert this user instance to JSON format, you simply use:

# Using .dict()
user_dict = user.dict()
print(user_dict)

# Using .json()
user_json = user.json()
print(user_json)

.dict() vs. .json(): What’s the Difference?

While both methods serve the purpose of serialization, they do so in slightly different ways:

  • .dict(): This method converts the Pydantic model into a standard Python dictionary. The result can be pretty printed, modified, or further processed before being converted to JSON.

    {
    'id': 1,
    'name': 'Alice',
    'email': None
    }
  • .json(): This method converts the Pydantic model directly into a JSON-formatted string. This string can be directly sent as a response in web APIs or written to a file.

    '{"id": 1, "name": "Alice", "email": null}'

In summary, if you need a Python dictionary for further manipulation, go with .dict(). If you need a JSON string for transmission or storage, .json() is the way to go.

Excluding Null Values

One handy feature of the .dict() method is the ability to exclude null values from the resulting dictionary. You can achieve this by setting exclude_none=True. This is particularly helpful when you want to produce cleaner outputs by omitting keys with null values. Note that exclude_none only works with .dict() but not directly with .json(). However, you can combine both methods like this:

# Excluding null values using .dict()
user_dict_without_nulls = user.dict(exclude_none=True)
print(user_dict_without_nulls)
# Output: {'id': 1, 'name': 'Alice'}

# To convert to JSON after excluding nulls
user_json_without_nulls = user.json(exclude_none=True)
print(user_json_without_nulls)
# Output: '{"id": 1, "name": "Alice"}'

There you have it! Leveraging Pydantic’s .dict() and .json() methods makes converting data models to JSON a breeze, and excluding null values ensures that your output remains clean and concise. Experiment with these methods in your own projects to see the benefits they bring to data serialization and deserialization.


Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC