From b8a10fdb3a828f2c12b982fccf73a5d947760d77 Mon Sep 17 00:00:00 2001 From: Simon Ser Date: Mon, 10 Oct 2022 19:17:30 +0200 Subject: [PATCH] Handle arrays in schema type --- cmd/jsonschemagen/main.go | 7 +++++-- schema.go | 21 ++++++++++++++++++++- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/cmd/jsonschemagen/main.go b/cmd/jsonschemagen/main.go index 0fd2207..dde8ebe 100644 --- a/cmd/jsonschemagen/main.go +++ b/cmd/jsonschemagen/main.go @@ -52,8 +52,11 @@ func resolveRef(def *jsonschema.Schema, root *jsonschema.Schema) *jsonschema.Sch } func schemaType(schema *jsonschema.Schema) jsonschema.Type { - if schema.Type != "" { - return schema.Type + switch { + case len(schema.Type) == 1: + return schema.Type[0] + case len(schema.Type) > 0: + return "" } var v interface{} diff --git a/schema.go b/schema.go index f5ada15..fd42c59 100644 --- a/schema.go +++ b/schema.go @@ -17,6 +17,25 @@ const ( TypeInteger Type = "integer" ) +type TypeSet []Type + +func (ts *TypeSet) UnmarshalJSON(b []byte) error { + if b[0] == '[' { + type rawTypeSet TypeSet + out := (*rawTypeSet)(ts) + return json.Unmarshal(b, out) + } else { + var t Type + err := json.Unmarshal(b, &t) + if err != nil { + *ts = nil + } else { + *ts = []Type{t} + } + return err + } +} + type Schema struct { // Core Schema string `json:"$schema"` @@ -51,7 +70,7 @@ type Schema struct { PropertyNames *Schema `json:"propertyNames"` // Validation - Type Type `json:"type"` + Type TypeSet `json:"type"` Enum []interface{} `json:"enum"` Const interface{} `json:"const"`