Skip to content

feat(schema): unmarshal JSON back into Schema - #1108

Open
ChrisJr404 wants to merge 1 commit into
danielgtaylor:mainfrom
ChrisJr404:schema-unmarshal-json
Open

feat(schema): unmarshal JSON back into Schema#1108
ChrisJr404 wants to merge 1 commit into
danielgtaylor:mainfrom
ChrisJr404:schema-unmarshal-json

Conversation

@ChrisJr404

Copy link
Copy Markdown

Working towards #1016 (parsing a huma-generated document back into huma structs), I hit this: Schema has a custom MarshalJSON but no UnmarshalJSON, so a schema it emits cannot be read back with encoding/json.

Two things break the round-trip:

type is written as ["string", "null"] when the schema is nullable, which fails to unmarshal into the string Type field ("cannot unmarshal array into Go struct field Schema.Type of type string").

$ref and any x- extensions are silently dropped, since Ref has no matching JSON tag and extensions are only handled by the custom marshaler.

This adds UnmarshalJSON as the inverse of MarshalJSON: it accepts type as either a plain string or the [type, "null"] array (setting Nullable), reads $ref into Ref, and collects unknown keys into Extensions the same way they are written back out. Marshaling is unchanged.

Added round-trip tests covering the nullable type array, refs, extensions, nested objects, and the invalid-type error path.

Schema has a custom MarshalJSON that writes `type` as a `[type, "null"]`
array when nullable and inlines extensions, but no matching UnmarshalJSON,
so a schema it produced could not be read back: the nullable type array
failed to unmarshal, and `$ref` plus `x-` extensions were silently
dropped. Add UnmarshalJSON as the inverse so schemas round-trip through
encoding/json.
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