Skip to content
DevTinyTools

JSON to Python Class Generator

Turn a JSON response into Python models that actually load it: keyword keys renamed instead of crashing, snake_case fields wired back to the wire names, and Optional only where the data justified it.

Runs entirely in your browser — your JSON is never uploaded.

BaseModel with Field(alias=...) so snake_case fields still read the wire keys.
0 chars
0 lines

Models target Python 3.9 or newer — that is the first release where list[...] works in an annotation. Free generation covers up to 1,000,000 characters per document — what Pro adds. The JSON you paste never leaves the tab; inference runs in your browser.

How to generate Python models from JSON

  1. Pick Pydantic or dataclass Pydantic validates and aliases; dataclasses need no dependency. The JSON shape is the same, so switching tabs costs nothing.
  2. Paste a JSON object or array or load the example: two orders with keys named class and from, which a naive generator turns into invalid Python.
  3. Name the root class The name is normalised to a valid identifier, so my order becomes MyOrder rather than a syntax error.
  4. Copy or download the .py file Models are declared children-first, so the file imports and validates without calling model_rebuild().

Pydantic or dataclass: the choice changes what breaks later

Both outputs describe the same document, and the difference is where the failure lands. A Pydantic model rejects a wrong value at the boundary — Order.model_validate(payload) raises with the field path. A dataclass accepts it, and the mistake surfaces several functions later as an AttributeError or a nonsensical total.

  • Reach for Pydantic when the JSON comes from an API you do not control. Validation, aliasing and JSON Schema export are exactly the three things you would otherwise hand-roll.
  • Reach for a dataclass when the structure is internal, when import time matters, or when a third-party dependency is not allowed — it is in the standard library and adds no install step.
  • Either way the field types come from the same inference: every array element is sampled and merged, so a key that only some records carry is optional in both outputs.

One caveat that applies to both: a dataclass has no aliases. The generated file keeps the original key in a trailing comment, and loading raw JSON into it needs a small adapter (or a library such as dacite). Pydantic does that job for free, which is why it is the default tab.

class, from and import are not valid field names

Real APIs send keys named class, from, import and in. Written as fields they are SyntaxErrors, so a generator that copies the key verbatim produces a file that cannot even be imported. The generator appends a trailing underscore — class_, from_ — and records the real key in Field(alias=...).

Names the model base already owns get the same treatment. A JSON key of model_config would shadow Pydantic's own configuration attribute, and self collides with the first parameter of every method, so both become model_config_ and self_.

Renaming without the alias is the trap worth naming: Pydantic ignores unknown keys by default, so a document with class and a model expecting class_ does not raise — the field is simply absent, and a required one fails with a message that points at the Python name you never sent.

Three states, and only one of them deserves a default

JSON distinguishes a key that is absent from a key that is present and null, and the generated models keep that distinction instead of flattening it:

  • Present in every sampled record, never null → str, int, float: a plain required field.
  • Present in every record, null in at least one → Optional[str] with no default. Pydantic still treats it as required, which is correct: the key must be there.
  • Missing from at least one record → Optional[str] = None. This is the only case where the value may be absent entirely.

The dataclass output carries an extra constraint the Pydantic one does not. Python evaluates default arguments in declaration order, and a dataclass raises TypeError: non-default argument follows default argument the moment the module is imported if a field with a default sits above a field without one. Since every optional field has = None, they are emitted last. The file imports cleanly; the field order simply stops matching the JSON.

snake_case fields, wire names preserved

orderId, orderID and order id all become order_id. That is what PEP 8 asks for and what ruff's N815 enforces, and it is also how Python code reads in practice. Two keys that collapse onto the same name are suffixed, so a document carrying both order id and order-id keeps both fields.

Pydantic needs two pieces to make the rename lossless: Field(alias="orderId") on the field, and populate_by_name=True in model_config. The alias alone makes the wire key the only accepted name, so Order(order_id=1) fails validation — a surprise when your own code, not an HTTP response, is the caller. Both are emitted together, and only for models that contain at least one alias.

int is exact — but the trip through JSON is where precision is lost

Python integers have no fixed width, so a 19-digit order ID is stored exactly by the generated int. That is a real advantage over the TypeScript output, where the same value is a float64 and rounds.

It does not rescue the tool, though, because the JSON text is parsed with JSON.parse before inference runs, and JavaScript stops being exact above 253−1. An ID that long is already rounded by the time it reaches the generator. Keep identifiers above that limit as strings in the payload — the precision guide walks through the arithmetic and the workarounds.

Mixed numeric types follow the same policy as the other generators here: a field that held both whole and fractional numbers widens to float, and a field that held a number and a string becomes Union[str, float] rather than a guess.

DevTinyTools Pro

The free generator handles the payloads most people paste by hand. Pro raises the per-document cap to 10,000,000 characters, which is roughly 10 MB of JSON — enough for a full API dump instead of a single response.

  • 10,000,000-character documents, roughly 10 MB of JSON
  • The same Pro licence unlocks every tool on the site — TypeScript, Go, Java, C#, schemas, batch ZIP export
  • Priority fixes — generation bugs move to the front of the queue

Pro is $29 one-time — a lifetime licence, sold through Lemon Squeezy as merchant of record, so VAT and sales tax are handled for you. Pro is a licence key, not an account: Buy DevTinyTools Pro, then activate it below and the higher limit unlocks in this browser.

Frequently asked questions

Should I use Pydantic or a dataclass?
Pydantic if the data comes from outside your program: it validates on the way in, coerces obvious mismatches, honours the aliases that keep snake_case fields bound to camelCase keys, and exports a JSON Schema. A dataclass if the data is produced and consumed inside your own code and you want no third-party dependency at all. The same JSON generates both, so you can switch tabs and compare before deciding.
Why is a field called class_ instead of class?
Because class is a Python keyword and class: str is a SyntaxError, not a warning. The generator appends a trailing underscore, which is the convention PEP 8 recommends, and moves the original key into Field(alias="class"). Without that alias Pydantic would look for a field named class_, find no such key in the document, and drop the value silently.
What does model_config = ConfigDict(populate_by_name=True) do?
An alias is exclusive by default in Pydantic v2: with Field(alias="orderId"), Order(orderId=1) works and Order(order_id=1) does not. populate_by_name=True accepts both spellings, so deserialisation keeps reading the wire format while your own code and tests can use the Python name. It is emitted only for models that actually contain an alias.
Why do some Optional fields have = None and others do not?
The two cases are different. A key that some array elements omitted becomes Optional[str] = None: absent is legal, so there is a default. A key that every element carried but one of them set to null becomes Optional[str] with no default: the key is still required, it is only the value that may be None. Collapsing both into = None would accept documents that are actually malformed.
Why did the dataclass fields change order?
A dataclass raises TypeError: non-default argument follows default argument at import time if a field with a default is declared above one without. Optional fields carry = None, so they are moved to the end of the class, keeping their relative order. The generated file imports cleanly because of that reordering; the cost is that field order no longer matches the JSON.
Do long integer IDs lose precision?
Python integers are arbitrary precision, so the generated int holds a 19-digit ID exactly. The limit is upstream of this tool: the text you paste is parsed with JSON.parse, and JavaScript numbers stop being exact above 2^53-1, so a longer integer is already rounded before inference sees it. Send large IDs as strings if they must survive the trip, which is also what the TypeScript and Go outputs need.
Why is every field snake_case, and can I turn that off?
snake_case is what PEP 8 and linters such as ruff expect, and orderId as a field name trips N815. Turning the alias option off keeps the snake_case names but drops the mapping back to the JSON keys, which is only useful when the keys already match or when you rename them yourself at the parse boundary.
Is my JSON uploaded anywhere?
No. Parsing, inference and code generation all run in this tab. The file picker uses FileReader, and no network request is made while generating — you can confirm that in your browser's network panel.
JSON RepairFix broken JSON from an assistant or a config file: fences, comments, single quotes, trailing commas, Python literals and truncated tails — with every change reported.JSON Formatter & ValidatorPretty-print JSON with 2 or 4 space indentation, check the syntax and copy or download the result.JSON ValidatorCheck whether a JSON document is valid and see exactly where the parser stopped.JSON MinifierStrip whitespace from JSON and see how many bytes the minified output saves.JSON Diff CheckerCompare two documents and list every added, removed and changed value with its path.JSON Escape & UnescapeTurn raw text into a JSON string value, or decode backslashes and \u escapes back into readable text.JSON to CSV ConverterTurn an array of JSON objects into a CSV file you can open in a spreadsheet.JSON to TypeScript GeneratorGenerate TypeScript interfaces from a JSON sample, with optional properties and unions inferred from every array element.JSON to Go Struct GeneratorGenerate Go structs from a JSON sample, with json tags, int64 or float64 widths, pointers for null fields and omitempty for optional keys.CSV to JSON ConverterConvert CSV to JSON with RFC 4180 parsing, delimiter detection, dotted headers unflattened into nested objects and numbers converted only when they round-trip exactly.JSON to Java POJO GeneratorGenerate Java classes from JSON: primitives for required values, boxed types for optional and nullable ones, @JsonProperty for renamed keys and nested static classes.JSON to YAML Converter (and back)Convert JSON to YAML or YAML to JSON in both directions, with multi-document support, error line numbers and YAML 1.2 typing rules.JSON to C# Class GeneratorGenerate C# classes from JSON with nullable annotations taken from every record, initialisers that avoid CS8618 and [JsonPropertyName] for each wire key.JSON to JSON Schema GeneratorTurn a JSON sample into a draft 2020-12 schema: required keys, nullable unions and nested $defs.