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
truewheninstancesatisfiesschema, otherwisefalse. 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
JSONSchemaCompiled schema wrapper. Construct with
new JSONSchema( schema: ... )or passoptionsas a named field.Common methods:
is_valid( instance )Boolean validation with short-circuiting.
validate( instance )Full validation returning a
ValidationResult.
ValidationResultThe structured result returned by
validate.valid()returns the boolean status.errors()returns an array ofValidationErrorobjects.to_Dict()converts to a Basic-style output shape.ValidationErrorBase class for validation errors. The canonical methods are
keywordLocation(),absoluteKeywordLocation(),instanceLocation(),error(),keyword(),details(), andto_Dict().Errors are grouped under
MissingValueError,UnexpectedValueError, andWrongValueError. The module exports specific subclasses for individual keywords such asRequiredPropertyError,TypeMismatchError,MaximumError,PatternError,AdditionalPropertiesError,OneOfError, andReferenceResolutionError.SubschemaErrorError class used for the message
A subschema had errors.. Itssuberrors()method returns weak links to the errors produced inside the subschema.SchemaRegistryRegistry for schema resources, anchors, and references. It is usually managed by
JSONSchema, but may be supplied inoptionswhen several schemas share references.HTTPResourceLoaderReference loader for HTTP and HTTPS resources. It is used only when supplied directly or when
allow_networkis true.FormatRegistryRegistry of
formatvalidators. A custom registry may be passed with theformatsorformat_registryoption.RelativeJSONPointerParser and evaluator for Relative JSON Pointers. This class is exported because JSON Schema uses the syntax for the
relative-json-pointerformat and because it is useful with schema-adjacent data tools.
OPTIONS
The options value may be a Dict or PairList.
base_uriBase URI used when registering the root schema and resolving relative references.
registryA
SchemaRegistryto use for$refand$dynamicRef.loaderA callable or object with a
load(uri)method used to fetch missing schema resources.allow_networkWhen true and no loader is supplied,
JSONSchemacreates anHTTPResourceLoader.formatsorformat_registryA
FormatRegistryused forformatchecks.format_assertWhen false,
formatis treated as an annotation and does not make validation fail.unknown_formatControls unknown formats. The default is
fail;ignoretreats 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
multipleOfare 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
durationformat 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.