s-knibbs / dataclasses-jsonschema

JSON schema generation from dataclasses
MIT License
166 stars 38 forks source link

Would it make sense to use `anyOf` for Union types instead of `oneOf` ? #129

Closed aeflores closed 2 years ago

aeflores commented 4 years ago

Right now, Union types are encoded as oneOf in the json_schema. This causes errors if you have a union of two types that serialize to a compatible representation.

The following code produces a validation error:

from dataclasses import dataclass
from dataclasses_jsonschema import JsonSchemaMixin
from enum import Enum
from typing import Union

class E(Enum):
    A= 'a'
    B= 'b'

@dataclass
class Data(JsonSchemaMixin):
    field : Union[E,str] = E.A

a=Data()
a.to_dict(validate=True)

This is because E.A is serialized to 'a' which is both a valid E and a valid str. I think the proper validation here would be to use anyOf. What do you think?

emcastro commented 3 years ago

The question is: what is the point of oneOf in JsonSchema? https://json-schema.org/understanding-json-schema/reference/combining.html#oneof

I do think validation should use anyOf.