Data conversion guides

Model JSON records with Python dataclasses or Pydantic

·

Use the inventory response to decide which attributes a Python model should require. Standard library dataclasses give you typed constructors, while a Pydantic model can validate incoming dictionaries using their JSON keys.

JSON to Python Dataclass

Compare a nullable note with a missing contact

Choose Load example and Generate Python with Standard library dataclass. Inventory is a List type alias, and each element is an InventoryItem. The item_id attribute has int type and metadata records the original item-id spelling.

The note field is Optional[str] with no default because both records include it and one gives null. Contact has Optional[str] and defaults to None because it is missing on one record. Enable Allow missing and nullable fields and note also defaults to None.

Python dataclasses documentationPython optional and union types

Validate the same inventory using JSON aliases

Select Pydantic v2 and leave the default options on Allow missing fields. The model now uses BaseModel and the item_id declaration uses Field with the item-id alias. In a project with Pydantic v2, pass the decoded response to TypeAdapter(Inventory).validate_python(data). Check that the first item has item_id 9007199254740993 and its nested warehouse has code west.

The Pydantic v1 output uses Config and parse_obj_as(Inventory, data) serves the array type. Choose the output that matches the installed project. For an object root use model_validate in v2 or parse_obj in v1 on the generated class instead.

Pydantic v1 model configurationPydantic v2 type adapters

Check numeric decoding before creating the object

Python int can represent the large sample ID without rounding. When the generator marks a high-precision fraction as Decimal, load JSON with json.loads and parse_float=Decimal to retain the original number before model construction.

A standard dataclass accepts constructor values as supplied. For nested dataclasses, construct a child instance from its mapping and then pass that instance to the parent. Use dataclasses.fields to inspect json_name metadata for renamed keys.

Python dataclasses documentationPython JSON decoding and parse_float

Common questions

Can a JSON property name be a Python keyword?

Yes. The generated attribute uses a safe identifier, and dataclass metadata or a Pydantic alias records the original JSON spelling.

Can a JSON field accept both a string and an integer?

The generated annotation uses Union for different observed kinds. Verify runtime coercion in the selected Pydantic version when that distinction matters.

Sources

Put it into practice.

Related guides