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
Newsletter
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

  • DZone's Article Submission Guidelines
  • Designing Memory Architecture for Stateful AI Agents: Short-Term Context and Long-Term Persistence
  • Part 4: Multi-Agent Orchestration — Pairing Goose With Quarkus Flow State Machines
  • MQTT, Kafka, NATS, or Zenoh? Choosing Edge-to-Cloud Messaging by Traffic Pattern

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
DZone Core CORE ·
Dec. 14, 23 · Analysis
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
16.1K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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