Skip to content

Generate from JSON Data

This code generator can create pydantic models from JSON Data. Under the hood, the generator uses GenSON to create JSON Schema from your input. The generated schema is then processed the in the same manner as JSON Schema input data.

Example

$ datamodel-codegen  --input pets.json --input-file-type json --output model.py

pets.json

{
  "pets": [
    {
      "name": "dog",
      "age": 2
    },
    {
      "name": "cat",
      "age": 1
    },
    {
      "name": "snake",
      "age": 3,
      "nickname": "python"
    }
  ],
  "status": 200
}

model.py

# generated by datamodel-codegen:
#   filename:  pets.json
#   timestamp: 2020-04-27T16:08:21+00:00

from __future__ import annotations

from typing import List, Optional

from pydantic import BaseModel


class Pet(BaseModel):
    name: str
    age: int
    nickname: Optional[str] = None


class Model(BaseModel):
    pets: List[Pet]
    status: int