jsonschema

package
v0.0.0-...-2ad74da Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 21, 2024 License: BSD-3-Clause Imports: 9 Imported by: 1

Documentation

Overview

Package jsonschema has utility functions for creating JSON Schema files from structs, and also for validating a JSON file against a schema.

These can be used together to validate input JSON files. To add validation to an existing type, e.g. `foo.MyConfiguration`, defined in `/foo.go`, the first step is to create sub-directory called `generate`, and in there have a singe appliation, `/foo/generate/main.go`, which uses go:generate to emit a schema file.

//go:generate bazelisk run --config=mayberemote //:go -- run .
package main

import (
  "go.skia.org/infra/go/jsonschema"
  "go.skia.org/infra/foo"
)

func main() {
  jsonschema.GenerateSchema("../schema.json", &foo.MyConfiguration{})
}

Note that running "go generate" on that file will drop `schema.json` file in the foo directory. Now add a `Validate` function to `foo.go` that uses the schema file, which we can make accessible by embedding it:

import (

  _ "embed" // For embed functionality.

)

//go:embed schema.json
var schema []byte

func ValidateFooFile(ctx context.Context, document []byte) error {
  validationErrors, err := jsonschema.Validate(ctx, document, schema)
  ...
}

Index

Constants

This section is empty.

Variables

View Source
var ErrSchemaViolation = errors.New("schema violation")

ErrSchemaViolation is returned from Validate if the document doesn't conform to the schema.

Functions

func GenerateSchema

func GenerateSchema(filename string, v interface{})

GenerateSchema writes the JSON Schema for 'v' into 'filename' and will exit via sklog.Fatal if any errors occur. This function is designed for use in an app you would run via go generate.

func Validate

func Validate(document, schema []byte) ([]string, error)

Validate returns null if the document represents a JSON body that conforms to the schema. If err is not nil then the slice of strings will contain a list of schema violations.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL