Search code examples
pythonjsonpydantic

Export Pydantic model classes (not instances) to JSON


I understand that Pydantic can export models to JSON, see ref. But in practice, this means instances of a model:

from datetime import datetime
from pydantic import BaseModel


class BarModel(BaseModel):
    whatever: int


class FooBarModel(BaseModel):
    foo: datetime
    bar: BarModel


m = FooBarModel(foo=datetime(2032, 6, 1, 12, 13, 14), bar={'whatever': 123})
print(m.json())
#> {"foo": "2032-06-01T12:13:14", "bar": {"whatever": 123}}

My question is parsing the class itself; so that the class could be understood by other languages, for example JavaScript.

Here is an example of what I'm envisioning:

{BarModel: {
   'whatever': 'int'}
}

{FooBarModel: {
  'foo': 'datetime', 
   'bar': {BarModel: {'whatever': 'int'}}
}

Is this possible using built-in Pydantic functionality?


Solution

  • Pydantic has built-in functionality to generate the JSON Schema of your models. This is a standardised format that other languages will have tooling to deal with. For example, with your definitions, running:

    import json
    print(json.dumps(FooBarModel.model_json_schema(), indent=2))
    

    would output:

    {
      "$defs": {
        "BarModel": {
          "properties": {
            "whatever": {
              "title": "Whatever",
              "type": "integer"
            }
          },
          "required": [
            "whatever"
          ],
          "title": "BarModel",
          "type": "object"
        }
      },
      "properties": {
        "foo": {
          "format": "date-time",
          "title": "Foo",
          "type": "string"
        },
        "bar": {
          "$ref": "#/$defs/BarModel"
        }
      },
      "required": [
        "foo",
        "bar"
      ],
      "title": "FooBarModel",
      "type": "object"
    }