datamodel-code-generator icon indicating copy to clipboard operation
datamodel-code-generator copied to clipboard

Feature request: support JSON Schema's `prefixItems` with precisely typed tuples instead of imprecise lists

Open kylebebak opened this issue 2 years ago • 2 comments

Is your feature request related to a problem? Please describe.

When generating models from JSON Schema it would be nice to be able to generate Tuple[] types using Tuple Validation.

Describe the solution you'd like

Consider the following schema:

{
  "$schema": "https://json-schema.org/draft-07/schema",
  "type": "object",
  "properties": {
    "a": {
      "type": "array",
      "prefixItems": [
        { "type": "number" },
        { "type": "string" }
      ],
      "minItems": 2,
      "maxItems": 2
    }
  },
  "required": ["a"]
}

Running datamodel-codegen --input test.json --input-file-type jsonschema --output-model-type typing.TypedDict --output model.py, this produces the output:

from __future__ import annotations

from typing import List

from typing_extensions import TypedDict


class Model(TypedDict):
    a: List

Ideally, it would produce the following instead:

from __future__ import annotations

from typing import Tuple

from typing_extensions import TypedDict


class Model(TypedDict):
    a: Tuple[float, str]

Describe alternatives you've considered

The only real alternative to typing an array with heterogenous types is to replace the array with an object whose properties can be typed individually. But changing a schema to use an object instead of an array isn't always possible.

kylebebak avatar Sep 12 '23 21:09 kylebebak

I would like to add my vote for this feature! Extremely useful!

tomjridge avatar Nov 30 '23 11:11 tomjridge