chain
py
JSON to Python error
⌃⏎ run · clear · / focus input
// about this tool

JSON to Python Online

Updated 2026-08-04

// how to use

  1. 1 Paste your JSON — a single object, or an array of them if you want optional fields detected.
  2. 2 Set the root name; nested objects are named from their key automatically.
  3. 3 Copy the dataclasses straight into a module, or hit "try example" to see the shape first.

// examples

A flat object
Input
{"user_id": 7, "name": "Ada"}
Output
@dataclass class Root with user_id: int and name: str
An array where one element has an extra key
Input
[{"id": 1}, {"id": 2, "note": "rush"}]
Output
note becomes `str | None = None` — present in one element only, so it is optional
A nested object
Input
{"address": {"city": "London"}}
Output
A separate `Address` dataclass, referenced from the root

// common uses

Turning an API response into typed models without hand-writing them Getting a starting point for a Pydantic or attrs model Documenting the shape of a payload someone sent you Spotting which fields are actually optional across a list of records

// faq

Why are some fields typed as `| None` with a default?
Because the key was missing from at least one element of an array you pasted. Sampling only the first element is how generated models end up wrong at runtime, so every element is merged and any key that is not in all of them becomes optional. Paste a single object and nothing will be marked optional.
Why are optional fields moved to the bottom of the class?
Python requires that fields with defaults follow fields without them — a dataclass that violates it raises TypeError at import, not at use. The order is rearranged so the generated file actually loads.
Does it use dataclasses or Pydantic?
Standard-library dataclasses, so the output has no dependencies. Converting to a Pydantic BaseModel is a one-line change per class if you need validation.
What happens to keys that are not valid Python names?
They are converted to a legal identifier and the original key is kept in a trailing comment, so you can add the alias your serialiser needs. Field names that merely shadow a builtin, like `id` or `type`, are left alone — those are legal and renaming them reads as a bug.
Is my JSON uploaded?
No. The conversion runs entirely in your browser, so the JSON never leaves your machine — safe for payloads from a real API.

Use this via API

Get a free API key →
curl -X POST https://thesnaptools.com/api/v1/tools/json-to-python \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"json":"{\"user_id\": 7, \"name\": \"Ada\"}"}'
Esc
↑↓ navigate open Esc close