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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • What Is Pydantic?
  • Process Mining Key Elements
  • How to Enable Azure Databricks Lakehouse Monitoring Through Scripts
  • Modify JSON Data in Postgres and Hibernate 6

Trending

  • Artificial Intelligence, Real Consequences: Balancing Good vs Evil AI [Infographic]
  • Immutable Secrets Management: A Zero-Trust Approach to Sensitive Data in Containers
  • From Zero to Production: Best Practices for Scaling LLMs in the Enterprise
  • Beyond ChatGPT, AI Reasoning 2.0: Engineering AI Models With Human-Like Reasoning
  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
11.6K 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

  • What Is Pydantic?
  • Process Mining Key Elements
  • How to Enable Azure Databricks Lakehouse Monitoring Through Scripts
  • Modify JSON Data in Postgres and Hibernate 6

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!