diff --git a/msgspec/_json_schema.py b/msgspec/_json_schema.py index be506e3f..f73c97a3 100644 --- a/msgspec/_json_schema.py +++ b/msgspec/_json_schema.py @@ -310,6 +310,13 @@ def to_schema(self, t: mi.Type, check_ref: bool = True) -> dict[str, Any]: if t.min_length is not None: schema["minProperties"] = t.min_length elif isinstance(t, mi.UnionType): + # don't wrap simple optionals in an anyOf + if len(t.types) == 2 and t.includes_none: + return ( + self.to_schema(t.types[0]) + if not isinstance(t.types[0], mi.NoneType) + else self.to_schema(t.types[1]) + ) structs = {} other = [] tag_field = None diff --git a/tests/test_schema.py b/tests/test_schema.py index e1b9df3c..c848fa6d 100644 --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -309,7 +309,7 @@ class Polygon(msgspec.Struct): "items": {"$ref": "#/$defs/Point"}, }, "name": { - "anyOf": [{"type": "string"}, {"type": "null"}], + "type": "string", "default": None, }, "metadata": { @@ -722,7 +722,7 @@ class Polygon: "items": {"$ref": "#/$defs/Point"}, }, "name": { - "anyOf": [{"type": "string"}, {"type": "null"}], + "type": "string", "default": None, }, "metadata": {