logo
GeekFormat

JSON to Python

Free online JSON to Python tool that automatically converts JSON data into Python @dataclass classes with type hints. Strings map to str, integers to int, floats to float, booleans to bool, arrays to List[T], nested objects become separate dataclasses, and null maps to Optional[Any]. Runs locally in your browser; copy with one click or download model.py. The generated code is compatible with Python 3.7+ standard library dataclasses and can be consumed directly by mainstream Python frameworks like FastAPI, Django REST framework, marshmallow, and cattrs, or used as strongly typed data structures in Jupyter Notebook.

Related

About JSON to Python: Turning JSON data into runnable dataclass models

JSON to Python is the process of converting JSON-formatted data (objects or arrays) into Python dataclass type definitions. Python is one of the most popular general-purpose programming languages today, widely used for web backends (FastAPI / Django / Flask), data science (pandas / scikit-learn), web scraping, DevOps scripts, machine learning, automated testing, and more. In development, you often need to convert JSON samples from API docs or actual responses into Python types; hand-writing classes is not only repetitive but also prone to incorrect field types, and this tool aims to automate that process.

dataclass is a standard library feature introduced in Python 3.7 (PEP 557), automatically generating magic methods like __init__, __repr__, __eq__ via the @dataclass decorator, reducing data class definitions from a dozen lines of boilerplate to a few lines of field declarations. This tool runs locally in the browser based on quicktype-core, using just-types and no-comments rendering options to generate clean dataclass code for Python. Output includes necessary imports like from dataclasses import dataclass and from typing import Any, List, Optional, usable directly with Python 3.7+ projects.

Type inference is the core of JSON to Python. The tool maps JSON primitive types to standard Python types: strings to str, integers to int, floats to float, booleans to bool, arrays to List[T] (elements inferred from first item), nested objects to separate @dataclass, null values to Optional[Any]. For nested objects, the tool automatically creates new dataclasses for each level, named by capitalizing field names in PascalCase, e.g., an address field generates an Address class, objects in items arrays generate an Item class.

Unlike some online tools that require uploading JSON to servers for processing, all computations for this tool happen in your browser. quicktype-core is loaded and executed via Web Worker; JSON parsing, type inference, Python code generation, and file downloads all happen locally, with no data sent to any server. This is especially important for JSON containing API keys, user privacy fields, or unreleased business structures; data is cleared from memory when you close the page.

The generated code can be placed directly into Python projects for use. dataclass is a standard library requiring no extra installation; the typing module is available from Python 3.5 onward. If using Python 3.9+, you can manually replace List[str] with built-in list[str], Optional[str] with str | None for more modern type hint syntax. If your project uses Pydantic for data validation (like FastAPI), simply change @dataclass to class Xxx(BaseModel): to seamlessly switch to Pydantic models.

Note that auto-generated code is a starting point, not an endpoint. The tool infers types from JSON samples and cannot determine precise business types (e.g., semantic types like URL, Email, ID are all uniformly inferred as str). For snake_case JSON fields, Python dataclass fields are generated as-is; you may need to manually change field names to snake_case or configure mapping via Pydantic alias_generator. We recommend using the generated result as a first draft, then fine-tuning field names, types, defaults, and validation logic according to project conventions.

Another comparison dimension worth noting is dataclass vs Pydantic BaseModel vs attrs vs TypedDict. dataclass is Python standard library, zero-dependency, pure data modeling, no runtime validation, suitable for internal data transfer objects (DTOs) and ORM models. Pydantic BaseModel adds type-driven validation, serialization, and settings management on top of dataclass, and is FastAPI's default data model layer. attrs is dataclass's predecessor, offering more configuration options (slots, validators, converters). TypedDict is a lightweight solution from the typing module, only providing type hints without runtime constraints, suitable for dict-compatible scenarios. This tool generates dataclass by default, which can be replaced with any of the above forms in your editor with one click.

Compared to online tools like Java to JSON / TypeScript to JSON, JSON to Python has unique value in the data science ecosystem. pandas functions like read_json, DataFrame.from_records, json_normalize often take lists of dict-like objects; scikit-learn's Pipeline.fit accepts data structures with field constraints; using dataclass to wrap JSON responses in Jupyter Notebook during exploratory analysis significantly improves code readability. Code generated by this tool integrates seamlessly with these ecosystems, using JSON samples as the single source of truth.

There are more alternative tools for JSON ↔ dataclass conversion in the Python ecosystem: marshmallow (focused on serialization/deserialization validation), cattrs (structured conversion library), pydantic (runtime validation + IDE hints), apischema (generates JSON Schema without dataclass decorator). Pure dataclasses generated by this tool are natural inputs for these libraries: after copying the generated class, marshmallow users can add Schema(Model), cattrs users can use cattrs.structure(data, Model) to complete conversion. We recommend using this tool as a starting point for type generation, then layering appropriate ecosystem libraries based on project architecture.

In CLI and automation scenarios, JSON to Python also has unique value. After argparse parses command line arguments, they usually need secondary wrapping into dicts before passing to business functions; replacing dicts with generated dataclasses makes scripts more robust. Similarly, wrapping configuration files (config.json / settings.json) with dataclass lets DevOps colleagues directly see field meanings and types in their IDE, catching configuration errors early with mypy in CI.

One often-overlooked detail is the balance between performance and maintainability. dataclasses generated by this tool are the best vehicle for immutable snapshots: adding (frozen=True) makes instances unmodifiable and safe for multi-threaded sharing; adding (slots=True) (Python 3.10+) reduces memory usage by about 40%. To avoid sharing the same empty list pitfall for generated List[str] fields, you must use field(default_factory=list) instead of = [], and code generated by this tool already follows this best practice.

Use Cases

  • REST API integration: Convert backend JSON responses to Python @dataclass, use with requests + json for strongly typed HTTP request parsing. With mypy or pyright, get real-time attribute completion and type checking in your IDE to avoid common spelling errors.
  • FastAPI request/response models: Convert example JSON from API interface documentation into Pydantic BaseModel templates to unify frontend and backend model definitions. We recommend enabling the response_model parameter in FastAPI projects to let OpenAPI docs auto-generate field examples and validation rules.
  • Django Ninja / DRF serializers: Convert JSON responses to dataclass, then manually add DRF's ModelSerializer or Ninja's Schema-derived classes. DRF's ModelSerializer can auto-generate validation rules based on dataclass; Ninja's Schema can also directly reuse this tool's output.
  • Web scraper data modeling: Convert JSON data scraped from web pages to dataclass to avoid field omissions and spelling errors caused by dynamic dict access. When used with async scraper libraries like requests-html, playwright, dataclass also reduces boilerplate for JSON deserialization.
  • Machine learning feature definition: Convert JSON schemas for scikit-learn / pandas training data to dataclass to standardize feature field names and types. sklearn Pipeline.fit(X, y) accepts data structures with type hints; dataclass + asdict is an efficient bridge for converting to/from pandas DataFrames.
  • Configuration file deserialization: Convert YAML/JSON configuration file examples to dataclass, use with Hydra / OmegaConf for strongly typed configuration reading. With Hydra's @dataclass decoration, configurations enjoy autocompletion in your IDE, avoiding common spelling errors and type inconsistencies in YAML configs.
  • Jupyter Notebook temporary structures: Convert JSON samples from exploratory data analysis to dataclass for easy attribute access and IDE completion in Notebooks. Wrapping JSON responses with dataclass in Notebooks significantly improves readability of exploratory analysis code, making subsequent refactoring into production modules easier.
  • Microservice interface definition: Convert example JSON request bodies for gRPC/HTTP services to Python types to unify server-side model definitions. After converting gRPC protobuf to JSON, converting to dataclass serves as a strongly typed model for backend services, aligned with frontend TypeScript types.
  • CLI tool development: Convert CLI configuration JSON examples to dataclass, use with argparse for configuration deserialization and validation. Converting argparse Namespace to dataclass only requires one line: dataclass(**vars(args)), which is safer than hand-written parsing logic.
  • Test data construction: Convert real JSON fixtures returned by backend to Python types, use dataclasses.replace for test data driving in pytest. pytest's parametrize decorator combined with dataclass constructs typed test fixtures with clearer failure messages.
  • Structured log parsing: Convert JSON logs captured by ELK / Loki to dataclass for easy filtering and alerting rules. After wrapping ELK JSON logs with dataclass, you can do precise field filtering and aggregation queries, safer than dict access.
  • Configuration center migration: Convert JSON configs from Apollo / Nacos / Consul to Python types for server-side configuration hot reloading. Apollo / Nacos JSON configs can be bidirectionally validated with dataclass, immediately detecting missing fields, type mismatches, and other issues on config changes.
  • Cross-language collaboration: When integrating Python backend with TypeScript frontend, convert the same JSON to Python dataclass and TS interface respectively to keep both sides consistent. In cross-language collaboration scenarios, Python backend + TS frontend share the same JSON sample, generating dataclass and interface respectively to keep field names consistent.
  • Database migration: Convert JSON documents exported from MongoDB / PostgreSQL JSONB fields to Python models as reference for ORM entity definitions. Converting MongoDB JSONB document exports to dataclass serves as field reference for ORM entities, easier to maintain than reading MongoDB documents directly.
  • Blockchain/Web3: Convert on-chain JSON RPC responses to Python dataclass for type wrapping in SDKs like web3.py. Ethereum SDKs like web3.py, eth-brownie all support dataclass-style return values, convenient for secondary wrapping.
  • Data science ETL: Convert upstream JSON data sources to dataclass, then use pandas DataFrame.from_records to convert to tables for downstream analysis. pandas DataFrame.from_records([asdict(d) for d in dataclass_list]) converts nested structures to tables in one line.
  • OpenAPI Schema validation: Convert example JSON from OpenAPI docs to Python models, then write Pydantic validation logic. OpenAPI example fields can be directly copied into this tool's input; generated Pydantic models automatically validate API documentation consistency.
  • Teaching examples: Convert example JSON to dataclass in Python courses to explain concepts like the typing module, type hints, automatic __init__ generation, etc. When explaining concepts like typing module, automatic __init__ generation, slots in Python courses, dataclass is the most intuitive demonstration vehicle.
  • Field naming conversion: Convert snake_case JSON API responses to dataclass, then manually change field names or use Pydantic alias_generator for field mapping. Pydantic's alias_generator can be configured in BaseModel for automatic camelCase ↔ snake_case mapping, avoiding hand-written aliases.

How to Use

  1. Paste JSON content into the left editor, or click the upload button to select a .json / .txt file
  2. Wait 400ms for auto-conversion; generated Python dataclass code will appear on the right
  3. If JSON is malformed, click the "Fix JSON" button to auto-repair common syntax issues
  4. Click "Copy" to paste into your project's models/ directory, or click "Download" to save as model.py

Features

  • Local browser conversion: JSON parsing and Python code generation happen entirely in your browser; input data is never uploaded to any server, so sensitive API responses are safe to use
  • dataclass annotated output: Generates standard Python classes decorated with @dataclass, usable directly in Python 3.7+ projects with from __future__ import annotations
  • Automatic type inference: str / int / float / bool / List[T] / Dict[str, Any] / Optional[Any] are automatically mapped from JSON values without manual field type specification
  • Automatic nested object splitting: Nested JSON objects generate separate @dataclass classes named with PascalCase field names (e.g., address -> Address), avoiding duplicate type definitions
  • Automatic List generic expansion: JSON arrays are automatically converted to List[T], with element types inferred from the first non-null element in the array, e.g., ["a","b"] -> List[str], [{...},{...}] -> List[Item]
  • Optional fields: null fields generate Optional[Any] as a fallback, ensuring type annotations correctly express potentially missing fields
  • 400ms debounce auto-conversion: Conversion triggers automatically after pasting, with real-time Python code preview on the right to reduce waiting and extra clicks
  • One-click JSON error repair: Automatically fixes common formatting errors like trailing commas, single quotes, missing quotes, then continues generating code once repaired
  • Copy and download: Copy all Python code with one click, or download as a model.py file to drop directly into your project root or models submodule
  • localStorage input history: Automatically saves recent inputs locally, so you can quickly resume editing after refreshing or accidentally closing the page
  • Responsive split-pane editing: Enter JSON on the left, view Python code on the right; supports drag-to-resize panel widths, adapted for large screens and mobile
  • Supports Pydantic / attrs / TypedDict secondary adaptation: Generated dataclasses can have BaseModel or attrs decorators added with one click to adapt to FastAPI, Django Ninja, pydantic-settings, and other frameworks

Code Examples

Python: Parsing API responses to generated dataclass with requests

python
# requirements.txt
# requests>=2.31

from dataclasses import dataclass
from typing import Any, List, Optional
import json
import requests


@dataclass
class Address:
    city: str
    zip: str


@dataclass
class User:
    id: int
    name: str
    active: bool
    address: Address
    tags: List[str]
    label: Optional[Any] = None


def main() -> None:
    resp = requests.get("https://api.example.com/users/1", timeout=10)
    resp.raise_for_status()

    # Directly deserialize JSON string to dataclass instance
    user: User = User(**resp.json())

    # Strongly typed access: IDE completion, mypy/pyright static checking
    print(f"{user.name} lives in {user.address.city}")
    print(f"tags: {user.tags}")


if __name__ == "__main__":
    main()

Python: FastAPI request body validation with generated models (Pydantic adapted)

python
# pip install fastapi 'pydantic>=2'

from typing import List, Optional
from fastapi import FastAPI
from pydantic import BaseModel


class Address(BaseModel):
    city: str
    zip: str


class User(BaseModel):
    id: int
    name: str
    email: str
    active: bool = True
    address: Address
    tags: List[str] = []
    label: Optional[str] = None


app = FastAPI()


@app.post("/users")
async def create_user(user: User) -> dict:
    # FastAPI automatically validates request body with User; field type/required errors return 422
    return {"id": user.id, "name": user.name}


@app.get("/users/{user_id}", response_model=User)
async def get_user(user_id: int) -> User:
    # response_model auto-serializes response; OpenAPI docs auto-generated
    return User(
        id=user_id,
        name="Alice",
        email="alice@example.com",
        active=True,
        address=Address(city="Beijing", zip="100000"),
        tags=["fastapi", "pydantic"],
    )

Python: Web scraper data modeling (dataclass + JSON deserialization)

python
from dataclasses import dataclass, asdict
from typing import List, Optional
import json


@dataclass
class Author:
    id: int
    name: str


@dataclass
class Article:
    id: int
    title: str
    url: str
    author: Author
    score: int
    tags: List[str]
    summary: Optional[str] = None


def parse_articles(raw_json: str) -> List[Article]:
    """Deserialize scraped JSON string into list of Articles."""
    payloads = json.loads(raw_json)
    return [Article(**payload) for payload in payloads]


if __name__ == "__main__":
    raw = '''[
        {
            "id": 1,
            "title": "Hello dataclass",
            "url": "https://example.com/p/1",
            "author": {"id": 10, "name": "Alice"},
            "score": 95,
            "tags": ["python", "typing"],
            "summary": "quick intro"
        }
    ]'''

    articles = parse_articles(raw)
    for art in articles:
        # IDE autocompletes author.name, tags, summary
        print(f"[{art.score}] {art.title} - {art.author.name}")
        print(f"  tags: {art.tags}")

        # Use asdict when dict form is needed (e.g., writing to MongoDB)
        doc = asdict(art)
        print(f"  mongo doc: {doc}")

Python: Machine learning feature definition (pandas + sklearn integration)

python
# pip install pandas scikit-learn

from dataclasses import dataclass, field, asdict
from typing import List, Optional
import json
import pandas as pd
from sklearn.ensemble import RandomForestClassifier


@dataclass
class FeatureSchema:
    """Sample feature schema, fine-tuned after generation by JSON to Python tool."""
    user_id: int
    age: int
    city: str
    plan: str
    monthly_spend: float
    active: bool
    tags: List[str] = field(default_factory=list)
    last_login: Optional[str] = None


def features_to_frame(samples: List[dict]) -> pd.DataFrame:
    """Convert JSON list to DataFrame, automatically using dataclass field names as column names."""
    rows = [asdict(FeatureSchema(**row)) for row in samples]
    df = pd.DataFrame(rows)
    # One-hot encode categorical fields
    df = pd.get_dummies(df, columns=["city", "plan"], drop_first=True)
    return df


def main() -> None:
    raw = json.loads('''[
        {"user_id": 1, "age": 25, "city": "Beijing", "plan": "pro", "monthly_spend": 99.0, "active": true, "tags": ["new"]},
        {"user_id": 2, "age": 40, "city": "Shanghai", "plan": "free", "monthly_spend": 0.0, "active": false, "tags": []}
    ]''')

    X = features_to_frame(raw)
    y = [1, 0]  # Assume labels: paying user / free user

    model = RandomForestClassifier(n_estimators=100, random_state=42)
    model.fit(X, y)

    print("feature_columns:", list(X.columns))
    print("importances:", dict(zip(X.columns, model.feature_importances_)))

Best Practices

JSON samples should include complete field example values whenever possible

The tool infers types from JSON samples; if a field is always null in samples, it will fall back to Optional[Any]. We recommend providing an example value for all key fields before generation (e.g., "description": "sample" infers str, "count": 0 infers int), then delete example values after generation to get precise types.

For complex JSON, prefer splitting into multiple dataclasses

This tool by default recursively expands nested objects into separate classes, but when a single file has more than 50 fields, we recommend manually splitting into submodules like models/user.py, models/order.py. This has three benefits: ① Faster compilation; ② Clearer division of labor among team members; ③ Easier handling of circular references.

Switch to Pydantic BaseModel when runtime validation is needed

If your project uses FastAPI or requires strict request body validation, we recommend immediately adapting to BaseModel after generating dataclass: change @dataclass to class Xxx(BaseModel):, change from dataclasses import dataclass to from pydantic import BaseModel, leave other field types unchanged. After Pydantic v2 was rewritten in Rust, its validation performance is even faster than dataclass.

Use mypy for type checking in CI

Add mypy src/ --strict command to your CI pipeline to catch field spelling errors, type inconsistencies, Optional misuse, and other issues. dataclasses generated by this tool fully comply with PEP 484 specifications and pass mypy with zero warnings. Combined with a pre-commit hook, developers can automatically check before committing.

Avoid mutable default values in dataclass fields

tags: List[str] = [] is a common error that causes all instances to share the same empty list. Code generated by this tool already handles this with field(default_factory=list), but always follow this rule when manually adding new fields after generation. Python's type system delays exposing this bug to runtime, and static checkers may not catch it either.

Downloaded model.py recommended to be placed in a separate models package

Recommended directory structure: src/models/__init__.py + src/models/user.py + src/models/order.py. This: ① Simplifies imports for business code with from models import User; ② Team can claim different dataclasses by module; ③ pytest fixtures can be imported uniformly in conftest.py.

Sensitive JSON must be processed locally

If JSON contains sensitive information like API keys, tokens, unreleased business structures, or unpublished product specifications, always use this tool (runs locally in browser) instead of online tools that require uploads. This tool sends no data to any server; all JSON content in memory is cleared when you close the page.

Enable slots in Python 3.10+ to save memory

If you need to instantiate many dataclasses (e.g., modeling millions of data points in web scraping), we recommend Python 3.10+ with @dataclass(slots=True) enabled. After enabling, instances no longer use __dict__, reducing memory usage by 30-40% and improving attribute access speed by about 20%. Code generated by this tool doesn't enable this by default; you can manually add slots=True after generation.

FAQ

How do I convert JSON to a Python dataclass?

Paste JSON content into the left editor, or click the upload button to select a .json / .txt file. The tool automatically calls quicktype-core within 400ms to generate Python code, showing @dataclass-decorated class definitions on the right. If the JSON is malformed, click the "Fix JSON" button to auto-repair before converting. If conversion doesn't trigger automatically within 400ms, manually click the Convert button in the toolbar.

Does the generated Python code include dataclass annotations?

Yes. The tool uses quicktype-core's just-types rendering mode to generate @dataclass decorators, from dataclasses import dataclass, and necessary imports like from typing import Any, List, Optional for Python, usable directly with Python 3.7+ standard library dataclasses. If you don't need dataclass, you can manually remove the decorator and import statements and rewrite as a plain class. For more aggressive types (like Decimal, UUID, datetime), we recommend using it with Pydantic BaseModel.

Which JSON data structures are supported?

All valid JSON structures are supported: primitive types (null, boolean, number, string), arrays (1D or multi-dimensional), nested objects (any depth). JSON objects generate a root dataclass; JSON arrays generate a root container of type List[RootClass]. Non-JSON values like JavaScript object literals, functions, Symbols, and undefined are not supported. quicktype-core also supports JSON Schema, JSON examples, and TypeScript inputs as type sources.

How do JSON field types map to Python types?

Strings map to str, integers to int, floats to float, booleans to bool, arrays to List[T] (element type inferred from first item), nested objects to separate @dataclass, null to Optional[Any]. See the "JSON Type to Python Type Mapping Cheat Sheet" below for specific mapping rules. Python 3.9+ can use built-in list[str], dict[str, Any] syntax without importing from the typing module.

What type do null values generate?

null values in JSON generate Optional[Any], indicating the field may be missing or have an uncertain type. If you already know the actual field type, you can provide an example value in the source JSON (e.g., "field": "" infers str), then change it to a more precise type like Optional[str] after generation based on business needs. If there are many null fields in your JSON, replace them with example values (like empty string, 0, false) in the source data for more precise inference results.

Do arrays convert to List?

Yes. JSON arrays are uniformly converted to Python List[T] generics, with element types automatically inferred from the first array item. For example, ["a","b"] generates List[str], [1,2,3] generates List[int], [{...},{...}] generates List[Item]. Empty arrays [] default to List[Any]. Multi-dimensional arrays are recursively expanded to List[List[T]], e.g., [[1,2],[3,4]] becomes List[List[int]].

How are nested objects handled?

Each nested object generates a separate @dataclass class, named by capitalizing the first letter of the field name. For example, if the root object contains an address field, both Root and Address dataclasses are generated, referenced in Root via address: Address. Objects with the same structure reuse the same type to avoid duplicate definitions. Same-structure objects are merged into one @dataclass class to avoid duplication; if you need to split them, manually copy into multiple classes after generation.

Can I customize the generated class name?

quicktype-core defaults to using the JSON source name (like User) as the root class name. You can manually modify class names and reference locations after generation. The downloaded model.py filename can also be renamed as needed when saving. The root class name defaults to JsonRootClass; you can use your IDE's Rename feature after generation to batch-rename to business-semantic names (like User, Order).

Can the generated code be used directly in a project?

Yes, it can be used directly, but ensure a Python 3.7+ environment (dataclasses is a 3.7 standard library). The code depends on the typing module, available in Python 3.5+. For more concise built-in generics list[str], dict[str, Any] in Python 3.9+, manually replace imported types like List[str]. If using modern package managers like uv, poetry, pdm, dependency declaration may differ slightly, but dataclass itself requires no extra dependencies.

Can I convert to Pydantic BaseModel instead of dataclass?

The tool generates @dataclass by default. If you need Pydantic BaseModel for FastAPI request body validation, you can: ① Change from dataclasses import dataclass to from pydantic import BaseModel; ② Change @dataclass to class Xxx(BaseModel):; ③ Change Optional[Any] to Optional[specific type] or leave as default. Pydantic v2 also supports directly inheriting from dataclass. Pydantic v2 also supports dataclass style: you can directly add the @dataclass decorator to a dataclass and pass it to FastAPI without inheriting BaseModel.

What are the complete steps to generate a FastAPI request body model?

FastAPI recommends Pydantic BaseModel. After generating a dataclass, rewrite in three steps: ① Change @dataclass to class Xxx(BaseModel):; ② Delete the dataclasses import, add from pydantic import BaseModel; ③ In FastAPI routes, receive the request body with user: Xxx = Body(...) for automatic validation. Advanced usage: Using Annotated[User, Body(...)] in FastAPI further controls request body media type and validation behavior.

Is data uploaded to servers? Is it private and secure?

Runs completely in your local browser. JSON parsing, Python code generation, and file downloads all happen in the browser via JavaScript; neither your input JSON data nor generated Python code are uploaded to any server, nor are they logged or cached in the cloud. Sensitive JSON containing API keys, tokens, or unreleased business fields is safe to use; data is cleared when you close the page. After closing or refreshing the page, all inputs, outputs, and localStorage history are cleared from memory with no residue.

Do I need to register or log in?

No. The tool is completely free, no registration, login, or authorization required. Open the page and use it; all features are available locally in your browser. The tool is completely free, ad-free, requires no authorization, and doesn't insert watermarks or tracking code into generated results.

What if JSON formatting is wrong?

The tool automatically detects JSON validity; on error, a red error message appears on the right with a "Fix JSON" button. Clicking it auto-repairs common errors: trailing commas, single quotes replaced with double quotes, missing quote completion for keys, comment removal, etc. After successful repair, it continues generating Python code. The repaired JSON doesn't change original semantics—it only fixes formatting; if the repair result isn't ideal, manually undo and re-paste.

Will converting large JSON cause lag?

There's no explicit line limit, but browser parsing and rendering of extremely large JSON will slow down. Recommendations: ① Split JSON and convert in batches; ② Focus on one nesting level at a time; ③ If you need to batch-generate 100+ classes, use the quicktype CLI tool (pip install quicktype) or datamodel-code-generator. datamodel-code-generator (pip install datamodel-code-generator) is another powerful CLI tool that supports direct Pydantic model output.

Troubleshooting

Prompt says "Please enter JSON data" or right side is empty

Left input box is empty or only contains whitespace. Ensure you've pasted valid JSON content, or click the upload button to select a .json / .txt file; you can also click the example button to load the built-in sample.

Prompt says JSON parsing failed

Common causes: trailing commas, single quotes instead of double quotes, keys without double quotes, containing JavaScript comments. Click the "Fix JSON" button to auto-repair some errors; if it still fails, first validate with a JSON formatting tool.

Generated field types aren't precise enough

The tool infers types from JSON samples, e.g., all integers are int, all strings are str. If you need more precise types like Decimal, datetime, UUID, EmailStr, manually modify field types after generation, and use Field constraints in Pydantic mode.

null field generated Optional[Any] instead of Optional[str]

Because JSON null can't infer specific type, the tool safely falls back to Optional[Any]. If you know the actual field type, replace it with an example value (e.g., "field": "") in the source JSON, regenerate, then manually change to Optional[str].

Runtime prompt says missing typing module

typing is Python 3.5+ standard library; dataclass is Python 3.7+ standard library. Check Python version: python --version. If version is too low, upgrade to Python 3.9+ for better generic syntax (list[str], dict[str, Any]).

Want to generate Pydantic BaseModel but don't want to manually rewrite

The tool outputs dataclass by default. If your project must use Pydantic, there are two approaches: ① After copying the generated result, use your IDE's Find & Replace to change @dataclass to class Xxx(BaseModel):, change from dataclasses import dataclass to from pydantic import BaseModel; ② Use the datamodel-code-generator CLI tool (pip install datamodel-code-generator) instead, which supports direct Pydantic model output.

Downloaded .py file gives import error in project

Possible causes: ① Python version below 3.7 (no dataclasses); ② Project has strict mypy mode but fields are untyped; ③ Class name conflicts with other modules in the project. Solutions: Upgrade Python to 3.9+, ensure all fields have type annotations, rename conflicting classes with import as.

snake_case JSON fields inconsistent with Python naming style

The tool keeps original JSON field names when generating Python fields. Python recommends snake_case naming, which is naturally consistent with JSON field style; if you need camelCase (e.g., interfacing with JavaScript frontend), manually change field names or configure alias mapping via Pydantic alias_generator.

Page lags when converting very large JSON

We recommend splitting JSON into multiple independent modules and converting separately, or only extracting the parts that need modeling. Rendering many dataclasses in the browser consumes significant memory; for JSON over 10MB, we recommend using the quicktype CLI tool (npx quicktype) or datamodel-code-generator.

FastAPI request body field validation fails (422 error)

FastAPI defaults to strict validation with Pydantic; missing fields or type mismatches return 422. Solutions: ① Change field type to Optional[type] = None to make fields optional; ② Use Field(default=..., description=...) to set defaults and documentation; ③ Check that request body Content-Type must be application/json.

Glossary

dataclass
Python 3.7+ standard library decorator (@dataclass) used to automatically generate magic methods like __init__, __repr__, __eq__. This tool generates @dataclass classes, e.g., @dataclass class User: id: int; name: str. Essentially decouples "data storage" from "data operations", letting classes focus on describing data fields while the decorator auto-generates boilerplate methods.
typing module
Python standard library for type hints, providing generic types like List, Dict, Optional, Any, Union. List[T], Optional[Any] generated by this tool come from the typing module. Python 3.9+ can directly use built-in list, dict. Alongside collections.abc, contextlib, etc., it's the core module for static type constraints in Python standard library; gradually became standard for large projects since PEP 484.
Optional[T]
Optional type from the typing module, equivalent to Union[T, None], indicating a field may be None. This tool maps JSON null to Optional[Any], which can be manually changed to more precise types like Optional[str]. Note that Optional[T] differs from T = None default: the former is a type-level None expression, the latter is a value-level default setting.
List[T]
Python generic list type. This tool automatically maps JSON arrays to List[T], e.g., string arrays map to List[str], object arrays to List[Item]. Python 3.9+ can write list[T]. The tool imports from typing by default, equivalent to Python 3.9+'s built-in list[T]; if your team prefers new syntax, replace the import with one click.
Any
Special type from the typing module indicating acceptance of any type. This tool defaults to using Any as a fallback for null values and empty arrays to avoid type inference errors. Frequent use of Any disables mypy / pyright checking; we recommend changing to precise types like Optional[str], List[int] after determining field types.
Pydantic BaseModel
Base data model class from the Pydantic library, providing runtime data validation, serialization, and deserialization. dataclasses generated by this tool can be adapted to BaseModel with one click for FastAPI request body validation. Pydantic v2 rewrote core validation logic in Rust, with 5-50x performance improvement over v1; dataclasses generated by this tool can also inherit BaseModel to enjoy this acceleration.
FastAPI
Modern Python web framework relying on Pydantic for automatic request body validation. dataclasses generated by this tool can serve as request/response model templates for FastAPI route functions. Based on Starlette + Pydantic, it auto-generates OpenAPI documentation and is one of the de facto standards for Python backend API frameworks today.
PEP 557
Python Enhancement Proposal defining the syntax and behavior of the dataclass decorator. Code generated by this tool fully complies with PEP 557 specifications. The proposal was initiated by Eric V. Smith in 2017, drawing design ideas from existing solutions like attrs and Haskell records.
Type Hint
Type annotations marked with : Type after Python function parameters and variables. dataclass fields generated by this tool all have type hints, enabling static type checking with mypy / pyright. Annotations themselves don't affect runtime behavior, only used for IDE hints, mypy / pyright static checking, and runtime validation libraries (like Pydantic).
PEP 484
Python type hint specification proposal defining the typing module and generic syntax. List[T], Optional[T], etc. generated by this tool follow PEP 484. Drafted by Guido van Rossum, Jukka Lehtosalo, Łukasz Langa, and others, it's the foundational document for Python's type hint system.
from __future__ import annotations
Deferred annotation evaluation statement introduced in PEP 563, storing all annotations as strings to avoid forward reference issues. Adding this line to dataclasses generated by this tool makes type annotation reference order irrelevant. When enabled, all annotations are lazily evaluated as strings, avoiding forward reference problems and decoupling dataclass field order from reference order.
model.py
Default filename downloaded by this tool, conforming to Python project conventions. Can be renamed to user.py, schemas.py, or other names matching project structure. Consistent with naming styles like Django's models.py, Flask's models.py; multi-model projects can split into submodules like user.py, order.py under a models package.

JSON Type to Python Type Mapping Cheat Sheet

The tool automatically infers corresponding Python types based on JSON value types:

JSON Value ExampleGenerated Python TypeDescription
nullOptional[Any]null value type uncertain; uses Optional[Any] as fallback, can be manually changed to precise types like Optional[str]
true / falseboolJSON booleans directly map to Python bool
42intJSON integers default to Python int (arbitrary precision)
3.14floatJSON floats default to Python float (double precision)
"hello"strJSON strings map to Python str (Unicode strings)
["a","b"]List[str]String arrays map to List[str]; Python 3.9+ can write list[str]
[1,2,3]List[int]Integer arrays map to List[int]
[{...},{...}]List[Item]Object arrays generate corresponding @dataclass from first element, then wrapped with List
[]List[Any]Empty arrays can't infer element type; uses Any as fallback
{...} nested objectSeparate @dataclassNested objects generate separate @dataclass classes named with PascalCase field names

Generated Python Code Structure Explanation

Typical code quicktype-core generates for Python includes the following parts:

Code PartExamplePurpose
from dataclasses import dataclassfrom dataclasses import dataclassImport dataclass decorator (Python 3.7+ standard library)
from typing import Any, List, Optionalfrom typing import Any, List, OptionalImport typing module type annotations: Any (any type), List (generic list), Optional (optional type)
@dataclass@dataclass class User:Decorator makes the class auto-generate methods like __init__, __repr__, __eq__
Field declarationsid: int name: strField definitions with type hints, automatically becoming __init__ parameters
List[T] fieldtags: List[str]Represents a JSON array field; element type inferred from first array item
Optional[Any] fieldlabel: Optional[Any] = NoneRepresents a field that may be null; default value None makes instantiation friendlier
Nested @dataclassaddress: AddressReferences other @dataclass classes in the same module, forming strongly typed structures

Python Data Modeling Solution Comparison

The tool outputs @dataclass by default, but there are multiple data modeling options in the Python ecosystem; choose based on project needs:

SolutionImport MethodRuntime ValidationTypical Scenarios
@dataclassfrom dataclasses import dataclassNone (type hints only)Internal DTOs, ORM models, pure data containers; zero-dependency first choice for Python 3.7+
Pydantic BaseModelfrom pydantic import BaseModelStrong (auto type conversion + custom validators)FastAPI request/response bodies, configuration file validation, cross-process data transfer
attrs @attr.sfrom attrs import frozen, fieldOptional validatorsHigh-performance scenarios requiring slots / frozen / custom converters
TypedDictfrom typing import TypedDictNone (type hints only; still dict at runtime)Lightweight type hints requiring full dict compatibility; e.g., mypy static checking
dataclasses-jsonfrom dataclasses_json import DataClassJsonMixinCan work with PydanticDeserialization scenarios adding .to_json() / .from_json() methods to dataclass
msgpack + dataclassimport msgpackNone (serialization layer)High-performance binary transfer scenarios (msgpack 30%-50% smaller than JSON)

Python Version and dataclass Feature Compatibility Table

Different Python versions have varying support for dataclass, typing, Pydantic; choose by version:

Python Versiondataclass Supporttyping SupportRecommended Use
3.6 and belowNone (requires pip install dataclasses)Basic typing availableNot recommended; upgrade to 3.9+
3.7 - 3.8@dataclass decoratorList[T], Optional[T] require import typingMinimum usable version; backward compatible with mainstream projects
3.9 - 3.10@dataclass + field + asdict completeCan use built-in list[T], dict[str, Any], PEP 585Recommended: modern type hint syntax + complete dataclass
3.10+@dataclass(slots=True) saves memoryPEP 604: int | None replaces Optional[int]Best: slots + modern union syntax
3.11+@dataclass + slots + frozen performance optimizationsAdvanced features like Self, TypeVarTuple, ConcatenateFirst choice for new projects; older projects can gradually upgrade
3.12+PEP 695 type parameter syntax (type List[T])Complete new type hint syntaxCutting-edge feature exploration; production environments recommend 3.11+

Privacy & Security

All operations of this JSON to Python tool happen completely locally in your browser: JSON parsing, Python code generation, and file downloads are all executed client-side via browser JavaScript; no JSON content, uploaded files, or generated code are sent over the network to any server. File uploads use the browser's native FileReader API to read directly into memory without passing through any intermediate services. No Cookie tracking is used, no user input or usage data is collected. After closing or refreshing the page, all input and output content is automatically cleared from memory. Suitable for processing JSON containing API keys, tokens, and sensitive business data.

Authoritative References