std/data/json/schema

Standard Library documentation

JSON Schema 2020-12 validation.

Module

Name
std/data/json/schema
Area
Standard Library
Source
modules/std/data/json/schema.zzm

NAME

std/data/json/schema - JSON Schema 2020-12 validation.

SYNOPSIS

  from std/data/json/schema import
    JSONSchema,
    RequiredPropertyError,
    TypeMismatchError,
    validate,
    valid;

  let person_schema := {
    type: "object",
    required: [ "name" ],
    properties: {
      name: { type: "string" },
      age:  { type: "integer", minimum: 0 },
    },
  };

  say( valid( person_schema, { name: "Ada", age: 37 } ) );

  let result := validate( person_schema, { age: -1 } );
  for ( let error in result.errors() ) {
    if ( error instanceof RequiredPropertyError ) {
      say( error.instanceLocation() _ ": " _ error.error() );
    }
  }

IMPLEMENTATION SUPPORT

This Pure Zuzu module is supported by all implementations of ZuzuScript. Network reference loading needs std/net/http, so it is available only in runtimes that provide that module.

DESCRIPTION

std/data/json/schema validates native Zuzu values against JSON Schema 2020-12 schemas. It is intended for already-decoded JSON data: schemas and instances are normally Dict, Array, strings, numbers, booleans, and null.

The validator also accepts some native collection types where the JSON model has a clear equivalent. PairList is treated as an object and preserves duplicate keys for keywords that need to inspect them. Set and Bag are treated as array-like values when order is not important, though ordered tuple validation is meaningful only for Array.

Validation can be requested in two forms. Boolean validation short-circuits after the first failure and returns true or false. Full validation collects errors and returns a ValidationResult whose errors are proper Zuzu objects with methods such as keywordLocation(), instanceLocation(), and error().

EXPORTS

Functions

  • valid( schema, instance, options := {} )

    Returns true when instance satisfies schema, otherwise false. This mode is the cheapest validation mode and stops as soon as a failure is known.

  • validate( schema, instance, options := {} )

    Returns a ValidationResult. This mode attempts to collect every independent validation error it can find.

Classes

  • JSONSchema

    Compiled schema wrapper. Construct with new JSONSchema( schema: ... ) or pass options as a named field.

    Common methods:

    • is_valid( instance )

      Boolean validation with short-circuiting.

    • validate( instance )

      Full validation returning a ValidationResult.

  • ValidationResult

    The structured result returned by validate. valid() returns the boolean status. errors() returns an array of ValidationError objects. to_Dict() converts to a Basic-style output shape.

  • ValidationError

    Base class for validation errors. The canonical methods are keywordLocation(), absoluteKeywordLocation(), instanceLocation(), error(), keyword(), details(), and to_Dict().

    Errors are grouped under MissingValueError, UnexpectedValueError, and WrongValueError. The module exports specific subclasses for individual keywords such as RequiredPropertyError, TypeMismatchError, MaximumError, PatternError, AdditionalPropertiesError, OneOfError, and ReferenceResolutionError.

  • SubschemaError

    Error class used for the message A subschema had errors.. Its suberrors() method returns weak links to the errors produced inside the subschema.

  • SchemaRegistry

    Registry for schema resources, anchors, and references. It is usually managed by JSONSchema, but may be supplied in options when several schemas share references.

  • HTTPResourceLoader

    Reference loader for HTTP and HTTPS resources. It is used only when supplied directly or when allow_network is true.

  • FormatRegistry

    Registry of format validators. A custom registry may be passed with the formats or format_registry option.

  • RelativeJSONPointer

    Parser and evaluator for Relative JSON Pointers. This class is exported because JSON Schema uses the syntax for the relative-json-pointer format and because it is useful with schema-adjacent data tools.

OPTIONS

The options value may be a Dict or PairList.

  • base_uri

    Base URI used when registering the root schema and resolving relative references.

  • registry

    A SchemaRegistry to use for $ref and $dynamicRef.

  • loader

    A callable or object with a load(uri) method used to fetch missing schema resources.

  • allow_network

    When true and no loader is supplied, JSONSchema creates an HTTPResourceLoader.

  • formats or format_registry

    A FormatRegistry used for format checks.

  • format_assert

    When false, format is treated as an annotation and does not make validation fail.

  • unknown_format

    Controls unknown formats. The default is fail; ignore treats unknown formats as annotations.

KNOWN OPTIONAL FIXTURE GAPS

The validator covers all required JSON Schema draft 2020-12 fixture files and many optional fixture files. The following optional fixture files are not yet promoted to the expected-passing set.

  • F<optional/cross-draft.json>

    References into older schema drafts are resolved, but draft-specific validation semantics for referenced historic drafts are not yet applied.

  • F<optional/float-overflow.json>

    Very large numeric values still use the host numeric model, so overflow and precision edge cases for multipleOf are not fully handled.

  • F<optional/ecmascript-regex.json>

    The JavaScript runtime passes this fixture, but the Perl and Rust runtimes do not yet emulate enough ECMAScript regular-expression semantics.

  • F<optional/format/duration.json>

    The duration format checker accepts basic duration shapes, but does not yet implement the full RFC 3339 duration grammar.

  • F<optional/format/hostname.json>

    Hostname validation is intentionally conservative and does not yet fully validate A-label, Punycode, and IDNA edge cases.

  • F<optional/format/idn-hostname.json>

    Internationalized hostname validation does not yet implement the full IDNA Unicode category, normalization, and bidirectional-text rules.

  • F<optional/format/ipv6.json>

    IPv6 validation is still simplified and misses some invalid compression and group-length edge cases.

  • F<optional/format/time.json>

    Time validation handles common RFC 3339 forms, but still has some leap-second and timezone-offset edge cases.

  • F<optional/format/uri.json>

    URI validation is stricter than a plain string check, but still accepts some invalid authority, userinfo, character, and port cases.

PORTABILITY

The module is pure ZuzuScript. Behaviour that depends on regular expression details or HTTP support may vary with the host runtime.

COPYRIGHT AND LICENCE

std/data/json/schema is copyright Toby Inkster.

It is free software; you may redistribute it and/or modify it under the terms of either the Artistic License 1.0 or the GNU General Public License version 2.