Genjsonschema is a simple JSON Schema generator.
It generates schemas in accordance with https://json-schema.org/draft-07/schema from JSON and YAML (some restrictions apply, see below).
See also the documentation at pkg.go.dev.
go get github.com/holgerjh/genjsonschema
Gnerate and print a JSON Schema from a simple JSON object:
package main
import (
"fmt"
"github.com/holgerjh/genjsonschema"
)
func main() {
from := []byte("{'foo': 'bar'}")
schema, err := genjsonschema.GenerateFromJSON(from, nil)
if err != nil {
panic(err)
}
fmt.Printf("%s", schema)
}
This will print the following (without whitespace):
{
"$schema": "http://json-schema.org/draft-07/schema",
"additionalProperties": false,
"properties": {
"foo": {
"type": "string"
}
},
"type": "object",
"required": [
"foo"
]
}
For YAML input, there exists an equivalent function named GenerateFromYAML
.
YAML is only supported as far as there exists an equivalent JSON expression. Notably, mappings may only use strings as keys.
The following is fine:
foo: "bar" # ok because key "foo" is of type string
The following is not fine:
42: "bar" # not ok because 42 is an integer
Providing the above YAML will raise an error.
The schema generated by Genjsonschema always defines a list using the anyOf
keyword for its items. In addition, lists won't be limited on length.
A schema generated from
[1, true]
will thus accept a list with an undefined number of integers, booleans, and combinations thereof, but will reject other element types such as string.
Given the schema generated from the JSON above, the following is accepted:
[true, 2, false]
But the following is not accepted:
[1, "foo"]