deftools.io Developer Tools

JSON → Pydantic Model

Generate Pydantic v2 BaseModel classes from JSON with type hints, Optional fields, and snake_case alias support. Paste JSON, get Python model definitions for FastAPI and data validation.

About this tool

Writing Pydantic v2 models by hand for every API response or config file is repetitive. Paste your JSON here and get the corresponding BaseModel classes — nested objects become separate model classes, arrays become list[...], and null values become Optional fields.

Example: {"id":1,"name":"Alice","address":{"city":"NYC"}} produces an Item model with id: int, name: str, and address: Address — plus a separate Address(BaseModel) class for the nested object. All models include proper type annotations and imports.

The generated models are a starting point — add validators, Field(ge=...) constraints, or ConfigDict settings for production use.

FAQ

How are nested objects handled?

A nested object under a key like "address" generates a separate model class named Address and references it as the field type on the parent. The root model name is configurable via the text input above.

What does "Nullable as Optional" do?

When enabled, any field with a null value in the sample becomes Optional[T] = None — meaning the field can be absent or explicitly null. Without it, null fields are typed as Optional[Any].

What does "Use Field(default=...)" do?

When enabled, every field gets a Field(default=...) marker instead of a Python default value. This is useful when you want to explicitly mark fields that must be provided versus those with defaults in a separate step.

Does it handle arrays of objects?

Yes. If the root is an array of objects, the first element defines the model shape and the root becomes a plain BaseModel. Nested objects inside array items are also extracted into their own model classes. Empty arrays fall back to list[Any].

What does "Snake case keys" do?

JSON keys are often camelCase (e.g. "isActive"), while Python convention uses snake_case. When enabled, camelCase keys are converted to snake_case (e.g. "is_active") in the generated model. The original JSON can still be parsed by Pydantic with populate_by_name=True.

What imports are included?

The generated code includes imports for BaseModel, Field, Optional, Union, and Any. The typing aliases match modern Python style. Remove or adjust imports based on your Python version and project setup.

More developer tools

Copied!