Trexmi
Converter Ready

JSON to Pydantic Model

Generate Pydantic v2 BaseModel classes from JSON with nested models, Python type hints, nullable options, and Field aliases for JSON keys.

Generate Pydantic v2 BaseModel classes Create named models for nested objects Infer list item and primitive types Create Field aliases for renamed JSON keys
Generated fields are required by default. The optional setting makes every field nullable and omittable; adjust fields individually to match the real API contract.
INPUT Sample JSON *
0 chars0 words0 lines

Tool settings

Ctrl / ⌘ + Enter
Pydantic v2 models Nested BaseModel classes with aliases for JSON keys that are not valid Python field names.
About the tool

What JSON to Pydantic Model does

JSON to Pydantic Model creates Pydantic v2 BaseModel classes from sample JSON. Primitive values become Python type hints, nested objects become named child models, and arrays use the first item to infer their item type.

JSON keys that are not safe Python field names are normalized and preserved with Field(alias=...). For example, user-id becomes the Python field user_id with an alias that still accepts the original JSON key. Fields are required by default. The optional setting changes every generated field to a nullable type with a default of None, which is only a broad scaffold and must be adjusted per field.

JSON converted into nested Pydantic v2 BaseModel classes
Generate typed Pydantic models while preserving non-Python JSON keys through aliases.

How to use

  1. Add sample JSON. Include representative nested objects, lists, nulls, booleans, integers, and decimal numbers.
  2. Name the model. Use a descriptive root class name such as OrderResponse.
  3. Choose required behavior. Keep the default for required fields or enable nullable and omittable fields as a starting point.
  4. Generate the classes. Child models appear before the root so annotations resolve without forward references.
  5. Review the contract. Add dates, UUIDs, enums, constraints, validators, aliases, and individual defaults based on authoritative API documentation.
Built for the task

Why use JSON to Pydantic Model?

Focused controls, predictable output, and a workflow designed around this exact transformation.

01

Pydantic v2 output

Generate BaseModel classes with built-in collection generics and union syntax.

02

Nested classes

Turn nested JSON objects into reusable named child models.

03

Real Field aliases

Preserve JSON keys with hyphens, spaces, leading digits, or Python keywords.

04

Explicit optional mode

Choose a strict required scaffold or a broad nullable and omittable scaffold.

Useful answers

Questions about JSON to Pydantic Model

Practical details about input, output, privacy, limits, and the best way to use this tool.

01 Does the tool generate Pydantic v2 models?

Yes. It uses BaseModel, built-in list[T] annotations, and T | None optional syntax appropriate for modern Python and Pydantic v2 projects.

02 Are fields required by default?

Yes. A sample contains observed fields but cannot prove which fields may be absent. Required is the safer deterministic starting point.

03 What does the optional setting do?

It makes every field nullable and supplies a default of None, so every field may be omitted. Review fields individually because nullable and missing are different API states.

04 How are JSON keys with hyphens or spaces handled?

They are converted to safe snake_case Python names and preserved with Field(alias="original-key").

05 How are arrays inferred?

A non-empty array uses its first item. Empty arrays become list[Any], and mixed arrays require a manually defined union or discriminated model.

06 Can it detect dates, emails, UUIDs, URLs, or constrained numbers?

No. JSON represents those semantic values as strings or numbers. Replace basic types with Pydantic types and constraints only when the contract supports them.

07 What happens when the JSON root is a scalar?

The generator wraps it in a field named value so the result remains a BaseModel.

08 Does generated code guarantee successful validation?

No. Run model validation against valid, missing, null, extra, malformed, and boundary payloads in the exact Python and Pydantic versions used by the application.

Learn JSON

Read the complete JSON Guide

Learn JSON objects, arrays, value types, validation, formatting, parsing, API workflows, and common syntax errors.

  • Objects, arrays, and values
  • Validation and formatting
  • API and parsing workflows
Read guide Practical explanations and examples

Examples

Generate nested BaseModel classes

The nested profile object becomes a child model declared before the root.

Input
Model: User
Optional: off
JSON: {"id":42,"name":"Ada","profile":{"city":"Kyiv","verified":true}}
Output
class UserProfile(BaseModel):\n    city: str\n    verified: bool\n\nclass User(BaseModel):\n    id: int\n    name: str\n    profile: UserProfile

Preserve difficult JSON keys

Safe Python fields use aliases so the original JSON property names remain accepted.

Input
Model: Account
JSON: {"user-id":7,"class":"premium","2fa enabled":true}
Output
class Account(BaseModel):
    user_id: int = Field(alias='user-id')
    class_: str = Field(alias='class')
    field_2fa_enabled: bool = Field(alias='2fa enabled')

Generate nullable and omittable fields

The broad optional mode adds both a nullable union and a None default to every field.

Input
Model: SearchResult
Optional: on
JSON: {"title":"Guide","score":0.98}
Output
class SearchResult(BaseModel):\n    title: str | None = None\n    score: float | None = None

Infer a list of objects

For a root array, the first object becomes the root model sample.

Input
Model: Product
JSON: [{"sku":"A-10","price":19.95}]
Output
class Product(BaseModel):\n    sku: str\n    price: float

How JSON becomes Python types

Strings, booleans, integers, and decimal numbers become str, bool, int, and float. Nested objects create child BaseModel classes. Lists use their first item to establish an initial item type. A null sample becomes Any because null alone does not reveal the intended non-null type.

JSON numbers do not carry domain meaning. A value such as 42 may be an identifier, quantity, enum member, bounded integer, or timestamp. Replace primitive annotations with constrained or semantic types based on the real schema.

Field aliases and Python identifiers

JSON property names can contain punctuation, spaces, leading digits, or Python keywords. Pydantic fields cannot. The generator creates a safe snake_case field and supplies the original property name through Field(alias=...). This is functional model metadata rather than a comment.

If two JSON keys normalize to the same Python field, a numeric suffix keeps the generated annotations unique and both aliases intact. Review these collisions because the similar names may still indicate an ambiguous source contract.

Required, missing, and nullable values

Required fields have no default. In the optional mode, every field receives a | None annotation and a None default, allowing both omission and null. Real APIs often require a mixture: some fields are required but nullable, some may be omitted, and others require a non-null value.

Edit defaults and annotations per field. Do not treat one global option as a faithful replacement for an OpenAPI or JSON Schema contract.

Inference limits and production checks

The generator does not infer validators, computed fields, serializers, configuration, strict types, enums, discriminated unions, aliases chosen by an API, recursive models, formats, numeric ranges, string limits, or extra-field policy. Arrays use only the first item and root empty arrays are rejected because no model fields can be inferred.

Prepare JSON with JSON Formatter, compare TypeScript output with JSON to TypeScript, create a frontend schema with JSON to Zod Schema, or inspect structural rules with JSON Schema Validator.

Official Pydantic documentation

Review the official Pydantic model documentation and Pydantic field and alias documentation.