Pydantic: Validate JSON in Python Without Guessing
Build a small Pydantic model, validate JSON, handle clear errors, and understand coercion before trusting data from forms, APIs, or AI tools.
By Velloreth
JSON is a data format, not a guarantee. A response can be valid JSON and still contain a missing field, the wrong type, or a number outside the range your application accepts. Pydantic lets Python code state those expectations in a model and check data at the boundary.
This tutorial builds a small reading-task model. There is no paid API, model account, database, or deployment. The example is deliberately local so the difference between parsing a document and validating its contents stays visible.
Why validation matters now
The October 2026 Talk Python discussion points to Pydantic as a bridge between outside text and application data. That is particularly relevant when a form, API, or AI tool supplies values your program did not create. The right lesson is to check inputs, not to assume that a schema makes an AI response true.
If JSON syntax itself is new, start with JSON, YAML, and TOML. If you already have a JSON document, the next question is what your application allows inside it. A schema turns that question into executable rules.
Set up a disposable environment
Use Python 3.10 or later for the syntax below. Create a virtual environment and install the v2 package line:
python -m venv .venv
Activate that environment with the command for your shell. On macOS or a typical Linux shell, use source .venv/bin/activate. In PowerShell, the usual path is .venv\Scripts\Activate.ps1; follow your machine’s execution policy rather than disabling it globally. Then run:
python -m pip install "pydantic>=2,<3"
Keep tutorial dependencies separate from an existing application’s environment. Once you decide to use the library in a real project, declare and lock dependencies using that project’s normal workflow.
Define the shape you actually need
Save this as validate_task.py:
from pydantic import BaseModel, Field
class ReadingTask(BaseModel):
title: str = Field(min_length=1)
minutes: int = Field(ge=1, le=180)
completed: bool = False
task = ReadingTask.model_validate_json(
'{"title":"Read one chapter","minutes":20}'
)
print(task.model_dump())
The model has a required title, a required duration between one and 180 minutes, and a completion flag with a default. Those limits are example application rules, not universal rules for reading tasks. Replace them only when you can explain the intended behavior.
Run the script. The resulting dictionary includes completed: False, even though the JSON omitted that field. A default changes how absence is handled. It is not the same thing as allowing every possible value.
Handle failure where data enters
Import ValidationError and handle the failure explicitly:
from pydantic import ValidationError
try:
ReadingTask.model_validate_json(
'{"title":"Read one chapter","minutes":0}'
)
except ValidationError as exc:
for issue in exc.errors():
print(issue["loc"], issue["type"])
Zero minutes violates the declared lower bound. The failure should stop the next step from consuming the invalid task. Do not catch the exception and quietly continue with the original unvalidated dictionary.
In a real application, choose an appropriate message for the reader and avoid logging full private payloads. An error structure can contain submitted values. Prefer a controlled field path and error category when that is enough to debug the problem. The site’s input validation guide discusses boundary checks more generally.
Understand conversion before you trust it
By default, Pydantic can convert some compatible inputs. An integer field may accept the string "20" and produce the integer 20. That can be convenient for form-like input, but it can also hide a mismatch between systems.
For a Python dictionary whose types must already be correct, test strict validation:
payload = {"title": "Read one chapter", "minutes": "20"}
try:
ReadingTask.model_validate(payload, strict=True)
except ValidationError:
print("minutes must already be an integer")
Strictness is a policy choice at a boundary. Do not switch it on merely because it sounds safer without checking real inputs. Some data types have different behavior when validated from JSON rather than Python objects, so consult the installed version’s documentation for those cases.
Shape is not meaning
The string "Read one chapter" satisfies this title rule. So does a misleading sentence, provided it is nonempty. A schema cannot know whether a task was really assigned, whether its author has permission, or whether a quoted fact is accurate.
For AI-generated JSON, validate structure first and verify important claims separately. Keep executable instructions and permission decisions outside the model’s untrusted text. A field called approved is only data unless your application has an independent reason to trust who set it.
For APIs, validation also does not replace authentication, authorization, rate limits, or persistence constraints. Read the site’s API authentication overview to keep those responsibilities distinct. A well-formed request can still come from the wrong person.
Build a useful test table
Try a valid task, a missing title, a zero duration, an oversized duration, and a numeric string. Write down which cases should pass before running them. Include a strict-validation test if your boundary rejects conversion. That table becomes a small regression suite rather than a one-time demo.
Do not rely on the exact wording of a full error message unless your application specifically promises it. Library releases can change presentation. Test the meaningful outcome: accepted data has the expected types and values, while rejected input cannot advance into application logic.
The most useful next step is one model at one real boundary, not turning every internal function into a model. Start where data enters, keep the rules visible, and expand only when the checks solve a concrete problem.
Keep source data and accepted data distinct
When debugging a model, compare a harmless sample of the incoming value with the accepted result. Ask whether a default was supplied, whether conversion occurred, and whether a rejected field is required by the actual application. That review catches an overly permissive model as well as an overly strict one.
Do not silently invent a replacement for a missing important value. A default is appropriate only when the application has a real policy for absence. For example, defaulting the completion flag to false is easy to explain; inventing a missing title would hide a problem that the caller should fix. Validation is most useful when rejected inputs lead to a clear next step rather than disappearing into a generic exception handler.
Sources and version scope
Checked October 26, 2026 against Pydantic’s model documentation and the October Talk Python discussion. Examples use the Pydantic v2 API. This guide makes no claim that validation establishes factual accuracy or measured keyword demand.