jsonschema Go Library

repository·boon·Indexed 22 days ago

https://github.com/santhosh-tekuri/jsonschema

A Go library for validating JSON and YAML data against JSON Schema specifications. It supports Draft 4, 6, 7, 2019-09, and 2020-12, featuring cycle detection, custom vocabularies, and content assertions. The package includes the jv CLI tool for validating instances against schemas with support for remote fetching via HTTP/HTTPS and local file loading.

Tokens
7.1K
Snippets
9
Records
53
Agent score
79%

What's inside jsonschema

  1. Overview of jsonschema library features

    boon

    The jsonschema library is a Go implementation for JSON Schema validation. Key features include:

    • Multi-Draft Support: Supports Draft 4, 6, 7, 2019-09, and 2020-12.
    • Cycle Detection: Detects infinite loops in $schema cycles and validation cycles.
    • Extensibility: Supports custom $schema URLs, custom regex engines, custom vocabularies, and custom format/content assertions.
    • Format Assertions: Includes built-in formats like uuid, email, ipv4, date-time, semver, and more. Note that format assertions must be explicitly enabled for drafts >= 2019-09.
    • Content Assertions: Supports contentEncoding (e.g., base64) and contentMediaType (e.g., application/json). These must be explicitly enabled for drafts >= 7.
    • Error Handling: Provides introspectable errors with a hierarchy, including an alternative display using # for locating errors.
  2. Use the jv CLI to validate JSON/YAML

    boon

    The jv CLI allows you to validate one or more JSON or YAML instances against a schema. It supports standard input via - and can fetch schemas via http(s) URLs.

    Usage Pattern: jv [OPTIONS] SCHEMA [INSTANCE...]

    Exit Codes:

    • 1: Validation errors
    • 2: Usage errors
  3. Implement a custom Vocabulary

    boon

    To extend the JSON Schema validator with custom keywords, you must implement the Vocabulary struct. A Vocabulary defines a set of keywords, their syntax, and their semantics.

    Key fields in the Vocabulary struct:

    • URL: The unique identifier for the vocabulary.
    • Schema: A schema used to validate the keywords introduced by this vocabulary.
    • Subschemas: A list of SchemaPath locations where subschemas introduced by this vocabulary can be found.
    • Compile: A function that takes a *CompilerContext and the keyword object (map[string]any) and returns a SchemaExt implementation. If the object contains no keywords from this vocabulary, return nil.
    type Vocabulary struct {
    	URL        string
    	Schema     *Schema
    	Subschemas []SchemaPath
    	Compile    func(ctx *CompilerContext, obj map[string]any) (SchemaExt, error)
    }
  4. Navigate JSON data using SchemaPath

    boon

    A SchemaPath is a sequence of Position tokens used to locate specific subschemas or data elements within a JSON structure. It allows for both direct access to specific properties or array indices and wildcard-style traversal of entire objects or arrays.

    Commonly used tokens within a SchemaPath include:

    • Prop: A specific property name in an object (e.g., "name").
    • Item: A specific integer index in an array (e.g., 0).
    • AllProp (*): A wildcard that matches all properties within an object.
    • AllItem ([]): A wildcard that matches all items within an array.

    You can use the collect method on a SchemaPath to traverse a JSON value and return a map of all matching locations, where keys are jsonPointers and values are the data found at those locations.

  5. Set a default JSON Schema draft version

    boon

    If a JSON schema is missing the $schema property, the compiler uses the latest draft supported by the library. You can force the compiler to use a specific draft version (e.g., Draft4) by calling DefaultDraft on the compiler instance.

    compiler := jsonschema.NewCompiler()
    compiler.DefaultDraft(jsonschema.Draft4)
  6. Reference the jv CLI options

    boon

    The following options are available for the jv CLI:

    OptionLong FlagDescription
    -c--assert-contentEnable content assertions with draft >= 7
    -f--assert-formatEnable format assertions with draft >= 2019
    --cacert--cacert <pem-file>Use the specified pem-file to verify the peer. The file may contain multiple CA certificates
    -d--draft <version>Draft version used when '$schema' is missing. Valid values: 4, 6, 7, 2019, 2020 (default 2020)
    -h--helpPrint help information
    -k--insecureUse insecure TLS connection
    -o--output <format>Output format. Valid values: simple, alt, flag, basic, detailed (default simple)
    -q--quietDo not print errors
    -v--versionPrint build information
    Usage: jv [OPTIONS] SCHEMA [INSTANCE...]
    
    Options:
      -c, --assert-content    Enable content assertions with draft >= 7
      -f, --assert-format     Enable format assertions with draft >= 2019
          --cacert pem-file   Use the specified pem-file to verify the peer. The file may contain multiple CA certificates
      -d, --draft version     Draft version used when '$schema' is missing. Valid values 4, 6, 7, 2019, 2020 (default 2020)
      -h, --help              Print help information
      -k, --insecure          Use insecure TLS connection
      -o, --output format     Output format. Valid values simple, alt, flag, basic, detailed (default "simple")
      -q, --quiet             Do not print errors
      -v, --version           Print build information
  7. Generate structured error output with OutputUnit

    boon

    To programmatically process validation failures, ValidationError can be converted into structured OutputUnit objects. There are two primary modes:

    1. Basic Output: A flat list of errors using BasicOutput() or LocalizedBasicOutput(p *message.Printer). This is useful for simple error reporting.
    2. Detailed Output: A hierarchical structure that mirrors the schema's nesting using DetailedOutput() or LocalizedDetailedOutput(p *message.Printer). This is useful for complex debugging where the relationship between errors and schema structure matters.

    An OutputUnit contains:

    • Valid: Always false for a ValidationError.
    • InstanceLocation: A JSON Pointer to the location in the input data.
    • KeywordLocation: A JSON Pointer to the location in the schema.
    • AbsoluteKeywordLocation: The full URL including the schema and keyword path (available in detailed/reference contexts).
    • Error: An OutputError containing the ErrorKind.
    • Errors: A slice of nested OutputUnit objects.
  8. Add schema resources for reference resolution

    boon
    Use AddResource(url string, doc any) to manually add a JSON document to the compiler's internal registry. This allows the compiler to resolve $ref pointers to this document. The url can be a file path or a URL (fragments are ignored), and doc must be a valid JSON value (e.g., a map[string]any).
  9. Use SchemaPath to collect data at specific locations

    boon

    The SchemaPath type implements a collect method that traverses a JSON value (any) based on the path's tokens. It returns a map[jsonPointer]any containing all values that match the path.

    If the path is empty, it returns the input value itself mapped to the current jsonPointer.

    Supported position types:

    • Prop(string): Targets a specific key in a map.
    • Item(int): Targets a specific index in a slice.
    • AllProp{}: Targets all keys in a map (represented by * in string format).
    • AllItem{}: Targets all elements in a slice (represented by [] in string format).
  10. Compile a JSON Schema

    boon
    The Compile(loc string) method compiles a JSON schema located at the provided loc. The loc can be a file path or a URL. If the schema is successfully compiled, it returns a *Schema object. For cases where you want to panic on failure (e.g., during global variable initialization), use MustCompile(loc string).