DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Five Nonprofit & Charity APIs That Make Due Diligence Way Less Painful for Developers
  • What Is Pydantic?
  • Beyond Partitioning and Z-Order: A Deep Dive into Liquid Clustering for Unity Catalog Managed Tables
  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever

Trending

  • The Agentic Agile Office: Streamlining Enterprise Agile With Autonomous AI Agents
  • How to Format Articles for DZone
  • A Hands-On ABAP RESTful Programming Model Guide
  • Architecting Zero-Trust AI Agents: How to Handle Data Safely
  1. DZone
  2. Coding
  3. Languages
  4. Mastering JSON Serialization With Pydantic

Mastering JSON Serialization With Pydantic

'Mastering JSON Serialization with Pydantic' guides you to seamlessly transform data between Python objects and JSON representations.

By 
Sameer Shukla user avatar
Sameer Shukla
DZone Core CORE ·
Dec. 14, 23 · Analysis
Likes (5)
Comment
Save
Tweet
Share
15.7K Views

Join the DZone community and get the full member experience.

Join For Free

Pydantic 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.

Python
 
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

JSON
 
{"id":1,"name":"Test user","age":12,"dept":"Information Technology"}


The model instance also has a method dict() that returns the Python dictionary object. 

Python
 
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.

JSON
 
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.

Python
 
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.

Python
 
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.

Python
 
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 than parse_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.
IT JSON Serialization Data (computing) Python programming language

Opinions expressed by DZone contributors are their own.

Related

  • Five Nonprofit & Charity APIs That Make Due Diligence Way Less Painful for Developers
  • What Is Pydantic?
  • Beyond Partitioning and Z-Order: A Deep Dive into Liquid Clustering for Unity Catalog Managed Tables
  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook