Skip to content

Accept array-typed type keyword in UnmarshalJSON - #5

Closed
ddevcap wants to merge 1 commit into
klippa-app:mainfrom
ddevcap:fix/type-array-unmarshal
Closed

Accept array-typed type keyword in UnmarshalJSON#5
ddevcap wants to merge 1 commit into
klippa-app:mainfrom
ddevcap:fix/type-array-unmarshal

Conversation

@ddevcap

@ddevcap ddevcap commented Jul 21, 2026

Copy link
Copy Markdown

Problem

JSON Schema (draft-07 and 2020-12, validation spec §6.1.1) allows the type keyword to be either a string or an array of strings, where an instance validates if its type matches any listed type. Schema.UnmarshalJSON decodes the keyword straight into the Type string field, so any spec-valid schema using the array form fails to parse:

json: cannot unmarshal array into Go struct field .SchemaAlt.type of type string

Fix

UnmarshalJSON now parses the keyword via json.RawMessage:

  • string form → assigned to Type as before;
  • array form → normalized to the equivalent anyOf branches (one {"type": ...} schema per entry). When the schema object already carries its own anyOf, the type union is wrapped as an allOf member instead, preserving the conjunctive semantics of sibling keywords (core spec §10.1).

The normalization is semantics-preserving: {"type": ["string","null"]} and {"anyOf": [{"type":"string"},{"type":"null"}]} accept exactly the same instances. Marshalling emits the anyOf form.

Covered by three new tests: plain array form, array form alongside an existing anyOf, and invalid type values still erroring.

JSON Schema (draft-07 and 2020-12, validation section 6.1.1) allows the
type keyword to be a string or an array of strings, where an instance is
valid when its type matches any listed type. UnmarshalJSON decoded the
keyword straight into the Type string field, so the array form failed
with "cannot unmarshal array into Go struct field".

Parse the keyword via json.RawMessage and normalize the array form into
the equivalent anyOf branches (wrapped as an allOf member when the
schema carries its own anyOf, preserving conjunction).
@ddevcap ddevcap closed this Jul 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant