Mock JSON · json.dumps() · Pydantic · FastAPI — 3 modes

Convert Python to JSON
Mock data, snippets
or framework guide.

Generate mock JSON from a Python class or dataclass, get json.dumps() snippets for every scenario, or get Pydantic v2, FastAPI and Django serialization patterns.

Your data never leaves your browser
Python class → mock JSON
json.dumps() · asdict() snippets
Pydantic v2 · FastAPI · Django
Always free
Python to JSON — 3 modes   100% client-side
Python class input
  Ready

      
Three ways to convert Python to JSON

Each mode targets a different Python workflow.

Mode 1 — Mock JSON

Paste a Python class, dataclass or Pydantic model and get realistic mock JSON. Works with type annotations, Optional fields and List types. Useful for pytest fixtures, API docs and Postman collections — no Python interpreter needed.

Input
id: int
name: str
active: bool
score: float
Output
{"id":1,"name":"Alice",
 "active":true,"score":9.99}
Mode 2 — json.dumps() snippets

Get complete Python code for every json serialization use case — basic, pretty-print, file I/O, custom encoders for datetime and Decimal, dataclass with asdict(), and Pydantic v2 model_dump_json(). Each snippet is production-ready.

Custom encoder
json.dumps(data, indent=2,
  default=lambda o:
    o.isoformat() if
    isinstance(o, datetime)
    else str(o))
Mode 3 — Framework patterns

Production-ready JSON serialization for Pydantic v2, FastAPI, Django REST Framework and Flask. Each snippet shows the recommended approach for the framework — including response models, serializer classes and jsonify() usage.

FastAPI
@app.get("/users/{id}",
  response_model=UserSchema)
async def get_user(id: int):
    return await get(id)
Python JSON serialization — method reference

The right method for each Python data type.

Data typeMethodNotes
dict, list, str, int, float, bool, None json.dumps(obj) Built-in, no imports needed beyond json. The default encoder handles all native JSON types.
dataclass instance json.dumps(asdict(obj)) dataclasses.asdict() recursively converts nested dataclasses. Import: from dataclasses import asdict.
Pydantic v2 model model.model_dump_json() Fastest option — Pydantic v2 uses Rust-based serialization. Returns a str, not bytes.
Pydantic v1 model model.json() Pydantic v1 legacy. Prefer model.model_dump_json() after upgrading to v2.
Custom class instance json.dumps(obj.__dict__) Quick option for simple classes. Use a custom default= function for full control.
datetime, Decimal, UUID json.dumps(obj, default=encoder) Pass a default= function that handles non-serializable types. See Mode 2 for complete example.
When do you need Python to JSON?
FastAPI and Pydantic v2

FastAPI uses Pydantic v2 for request validation and response serialization. Mode 3 gives you the complete FastAPI endpoint with response_model, Pydantic schema definition, and the model_dump_json() pattern for manual serialization — the fastest Python JSON library available.

pytest fixtures and test data

pytest fixtures often need JSON representations of Python objects for API testing. Mode 1 generates realistic mock JSON from your dataclass or Pydantic model — paste it as the expected response in assert response.json() == expected or create it as a JSON fixture file loaded with json.load().

Data export and ETL pipelines

Python data pipelines often need to export processed data as JSON files — for downstream consumers, S3 storage or API responses. Mode 2 gives you the file output pattern with proper encoding, ensure_ascii=False for Unicode and error handling.

Django REST Framework APIs

DRF serializers control exactly what fields are included in JSON responses. Mode 3 gives you the complete DRF serializer class with nested relationships, the ViewSet that uses it, and the @api_view pattern for function-based views.

Popular searches
python dict to json python to json python object to json python dict to json string python class to json pydantic to json python dataclass to json python list to json python dict to json file python to json online python object to json string pydantic to json schema python to json converter

Python parsed in your
browser. No interpreter needed.

The mock JSON mode uses a type annotation parser — no need to run Python. It handles dataclass, Pydantic, plain class and TypedDict annotations including Optional[T], List[T] and Union types. The snippets are generated from your selection without any API call.

The framework snippets reflect the actual recommended patterns from each framework's documentation — Pydantic v2's model_dump_json() (not the deprecated .json()), FastAPI's response_model pattern, and DRF's ModelSerializer with nested relationships.

Pydantic v2 specific
model_dump_json(), model_dump(), model_validate() — the new Pydantic v2 API, not the deprecated v1 methods most resources still show.
Custom encoder pattern
Handles datetime, Decimal, UUID and custom objects — the most common reason json.dumps() fails in real projects.
3 frameworks + stdlib
Pydantic v2, FastAPI, Django REST Framework and Flask — the four most common Python JSON serialization environments.
47 tools, always free
No file size limits, no watermarks, no account. Funded by non-intrusive display advertising only.
Frequently asked questions
Common questions about converting Python to JSON.
How do I convert a Python dict to JSON?
Use json.dumps(): import json; json_str = json.dumps(my_dict). For pretty output: json.dumps(my_dict, indent=2, ensure_ascii=False). For files: with open('output.json', 'w') as f: json.dump(my_dict, f, indent=2). The json module is part of Python's standard library.
How do I convert a Python dataclass to JSON?
Use dataclasses.asdict() with json.dumps(): from dataclasses import asdict; import json; json_str = json.dumps(asdict(obj), indent=2). asdict() recursively converts nested dataclasses to dicts. For a list: json.dumps([asdict(item) for item in items]).
How do I serialize a Pydantic v2 model to JSON?
Use model.model_dump_json() for a JSON string, or model.model_dump() for a dict. For a list: json.dumps([m.model_dump() for m in models]). Pydantic v2 uses Rust-based serialization — it's significantly faster than json.dumps(). Avoid the deprecated .json() and .dict() methods from Pydantic v1.
Why does json.dumps() fail with TypeError?
json.dumps() only handles native Python types: dict, list, str, int, float, bool, None. Common non-serializable types include datetime (use .isoformat()), Decimal (cast to float or str), UUID (cast to str) and custom class instances (use __dict__ or a custom default= function). Select the Custom encoder scenario in Mode 2 for the complete solution.
Is the Python to JSON converter free?
Yes, completely free. No file size limits, no account required. JSONshift is funded by non-intrusive display advertising.
Go up