Skip to content

Go module to generate JSON Schemas from JSON and YAML files.

License

Notifications You must be signed in to change notification settings

holgerjh/genjsonschema

Repository files navigation

genjsonschema

Test & Lint Go Report Card Coverage

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.

Install

go get github.com/holgerjh/genjsonschema

Examples

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.

Restrictions & Peculiarities

Restrictions on YAML input

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.

List interpretation

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.

Example

Given the schema generated from the JSON above, the following is accepted:

[true, 2, false]

But the following is not accepted:

[1, "foo"]

About

Go module to generate JSON Schemas from JSON and YAML files.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages