PTPureToolkit

Guide

How to Generate Pydantic v2 Models from JSON with Optional Fields

Learn how JSON examples become Pydantic v2 BaseModel classes, including aliases, nested objects, arrays, nulls, and Optional fields.

Start with representative JSON

JSON-to-model generation is only as accurate as the example you provide. If your API sometimes returns null, nested objects, arrays, or alternative shapes, include those cases in the sample. A tiny happy-path payload may produce a clean class, but it can hide fields that should be optional or unions that require manual review.

Pydantic v2 BaseModel classes are especially useful when you want validation at service boundaries. Generated classes give you a structured first draft with typed fields, nested models, and imports. You should still review naming, defaults, validators, and domain-specific constraints.

Nulls and Optional fields

A JSON null value usually means one of two things: the field is genuinely nullable, or the sample is incomplete. The local generator can turn nulls into Optional fields so the generated code remains usable for real API responses. That is helpful for integrations where nullable fields are common, such as profile metadata or external CRM payloads.

Do not rely on null inference alone for contract design. If a field is required by your business logic but happened to be null in a sample, tighten the generated model manually after reviewing the API documentation or production examples.

Aliases and Python identifiers

Many JSON APIs use camelCase, kebab-case, numeric prefixes, or reserved words. Those keys do not always make good Python attributes. A Pydantic model can keep Pythonic snake_case fields while preserving the original JSON key through Field(alias=...).

Alias generation is one of the main reasons to use a purpose-built generator instead of a simple JSON schema snippet. It keeps application code readable without losing compatibility with the upstream payload shape.

Use the embedded generator

The tool below parses JSON and generates Pydantic v2 code in your browser. Your sample payload is not sent to PureToolkit servers, analytics, or any AI service. Copy the output, run it through your formatter, and add validators where your domain requires stricter rules.

Embedded local tool

JSON to Pydantic v2 Model Generator

Options

List syntax: builtin list[str]

Generated Pydantic model

Generate a Pydantic model to see Python output.