karenetheridge/JSON-Schema-Modern

Validate data against a schema using a JSON Schema

22

stars

1,737

commits

Perl

primary language

Sep 9, 2026

updated

metacpan.org/release/JSON-Schema-Modern/
json-schema

README

=pod

=encoding UTF-8

=for stopwords schema subschema metaschema validator evaluator OpenAPI

=head1 NAME

JSON::Schema::Modern - Validate data against a schema using a JSON Schema

=head1 VERSION

version 0.645

I use a linearly-increasing version numbering scheme. No meaning should be
presumed or inferred from the version being less than 1.0.

=head1 SYNOPSIS

  use JSON::Schema::Modern;

  $js = JSON::Schema::Modern->new(
    specification_version => 'draft2020-12',
    output_format => 'flag',
    ... # other options
  );
  $result = $js->evaluate($instance_data, $schema_data);

=head1 DESCRIPTION

This module is a fully-compliant L<JSON Schema|https://json-schema.org/> evaluator and
validator, targeting the currently-latest
L<Draft 2020-12|https://json-schema.org/specification-links.html#2020-12>
version of the specification.

=head1 CONSTRUCTOR ARGUMENTS

Unless otherwise noted, these are also available as read-only accessors.

=head2 specification_version

Indicates which version of the JSON Schema specification is used during evaluation. This value is
overridden by the value determined from the C<$schema> keyword in the schema used in evaluation
(when present), or defaults to the latest version (currently C<draft2020-12>).

The use of the C<$schema> keyword in your schema is I<HIGHLY> encouraged to ensure continued correct
operation of your schema. The current default value will not stay the same over time.

May be one of:

=over 4

=item *

L<C<draft2020-12> or C<2020-12>|https://json-schema.org/specification-links.html#2020-12>, corresponding to metaschema C<https://json-schema.org/draft/2020-12/schema>

=item *

L<C<draft2019-09> or C<2019-09>|https://json-schema.org/specification-links.html#2019-09-formerly-known-as-draft-8>, corresponding to metaschema C<https://json-schema.org/draft/2019-09/schema>

=item *

L<C<draft7> or C<7>|https://json-schema.org/specification-links.html#draft-7>, corresponding to metaschema C<http://json-schema.org/draft-07/schema#>

=item *

L<C<draft6> or C<6>|https://json-schema.org/specification-links.html#draft-6>, corresponding to metaschema C<http://json-schema.org/draft-06/schema#>

=item *

L<C<draft4> or C<4>|https://json-schema.org/specification-links.html#draft-4>, corresponding to metaschema C<http://json-schema.org/draft-04/schema#>

=back

=head2 output_format

One of: C<flag>, C<basic>, C<strict_basic>, C<terse>. Defaults to C<basic>.
C<strict_basic> can only be used with C<specification_version = draft2019-09>.
Passed to L<JSON::Schema::Modern::Result/output_format>.

=head2 short_circuit

When true, evaluation will return early in any execution path as soon as the outcome can be
determined, rather than continuing to find all errors or annotations.
This option is safe to use in all circumstances, even in the presence of
C<unevaluatedItems> and C<unevaluatedProperties> keywords: the validation result will not change;
only some errors will be omitted from the result.

Defaults to true when C<output_format> is C<flag>, and false otherwise.

=for Pod::Coverage max_traversal_depth

=head2 max_depth

The maximum number of levels deep a schema evaluation may go before evaluation is halted. This is to
protect against accidental infinite recursion, such as from two subschemas that each reference each
other, or badly-written schemas that could be optimized. Defaults to 50.

=head2 validate_formats

When true, the C<format> keyword will be treated as an assertion, not merely an annotation. Defaults
to true when specification_version is draft4, draft6 or draft7, and false for all other versions, but this may change in the future.

Note that the use of a format that does not have a defined handler will B<not> be interpreted as an
error in this mode; instead, the undefined format will simply be ignored. If you instead want this
to be treated as an evaluation error, you must define a custom schema dialect that uses the
format-assertion vocabulary (available in specification version C<draft2020-12>) and reference it in
your schema with the C<$schema> keyword.

=head2 format_validations

=for stopwords subref

An optional hashref that allows overriding the validation method for formats, or adding new ones.
Overrides to existing formats (see L</Format Validation>)
must be specified in the form of C<< { $format_name => $format_sub } >>, where
the format sub is a subref that takes one argument and returns a boolean result. New formats must
be specified in the form of C<< { $format_name => { type => $type, sub => $format_sub } } >>,
where the type indicates which of the data model types (null, object, array, boolean, string,
or number) the instance value must be for the format validation to be considered.

Not available as an accessor; see L</add_format_validation>.

=head2 validate_content_schemas

When true, the C<contentMediaType> and C<contentSchema> keywords are not treated as pure annotations:
C<contentEncoding> (when present) is used to decode the applied data payload and then
C<contentMediaType> will be used as the media-type for decoding to produce the data payload which is
then applied to the schema in C<contentSchema> for validation. (Note that treating these keywords as
anything beyond simple annotations is contrary to the specification, therefore this option defaults
to false.) The decoded data is also reflected in L<JSON::Schema::Modern::Result/data>.

See L</add_media_type> and L</add_encoding> for adding additional type support.

=for stopwords shhh

Technically only draft4, draft6 and draft7 allow this and drafts 2019-09 and 2020-12 prohibit ever returning the
subschema evaluation results together with their parent schema's results, so shhh. I'm trying to get this
fixed for the next draft.

=head2 collect_annotations

When true, annotations are collected from keywords that produce them, when validation succeeds.
These annotations are available in the returned result (see L<JSON::Schema::Modern::Result>).
Not operational when L</specification_version> is C<draft4>, C<draft6> or C<draft7>.

Defaults to false.

=head2 scalarref_booleans

When true, any value that is expected to be a boolean B<in the instance data> may also be provided
as the scalar references C<\0> or C<\1> (which are serialized as booleans by JSON backends).

Defaults to false.

=head2 stringy_numbers

When true, any value that is expected to be a number or integer B<in the instance data> may also be
expressed as a string. This applies only to the following keywords:

=over 4

=item *

C<type> (where both C<string> and C<number> (and possibly C<integer>) are considered valid)

=item *

C<const> and C<enum> (where the string C<"1"> will match with C<"const": 1>)

=item *

C<uniqueItems> (where strings and numbers are compared numerically to each other, if either or both are numeric)

=item *

C<multipleOf>

=item *

C<maximum>

=item *

C<exclusiveMaximum>

=item *

C<minimum>

=item *

C<exclusiveMinimum>

=item *

C<format> (for formats defined to validate numbers)

=back

This allows you to write a schema like this (which validates a string representing an integer):

  type: string
  pattern: ^[0-9]$
  multipleOf: 4
  minimum: 16
  maximum: 256

Such keywords are only applied if the value looks like a number, and do not generate a failure
otherwise. Values are determined to be numbers via L<perlapi/looks_like_number>.
This option is only intended to be used for evaluating data from sources that can only be strings,
such as the extracted value of an HTTP header or query parameter, or a value from an XML document.
In the OpenAPI context, it is preferable to use an explicit C<type> keyword in the schema to
indicate the value should be deserialized as a number).

Defaults to false.

=head2 strict

When true, unrecognized keywords are disallowed in schemas (they will cause an immediate abort
in L</traverse> or L</evaluate>), with the exception of keywords starting with C<x->. Note that
this option is expected to become the default behaviour in future versions of JSON Schema.

Defaults to false.

=head2 with_defaults

When true, for any property name referenced by a C<properties> keyword, or array item referenced
by a C<prefixItems> keyword (or the array form of C<items> in earlier specification versions), that
does not exist in the object currently being evaluated, will result in an entry being added to the
C<defaults> property in the result object (see L<JSON::Schema::Modern::Result/defaults>),
indicating that the application may wish to add this default value to their instance data.

Defaults data accumulated in subschemas that are subsequently determined to be invalid are
discarded, with the final results from all subschemas accumulated together in one hash.  No attempt
is made to resolve conflicting entries (last one wins).

For example, this data instance:

  {
    "my_object": {
      "alpha": 1,
      "gamma": 3
    },
    "my_array": [
      "yellow"
    ]
  }

evaluated against this schema:

  type: object
  properties:
    my_object:
      type: object
      properties:
        alpha:
          type: integer
          default: 10
        beta:
          type: integer
          default: 10
        gamma:
          type: integer
          default: 10
    my_array:
      type: array
      prefixItems:
        - type: string
          default: red
        - type: string
          default: green

will result in an C<defaults> entry of:

  {
    '/my_object/beta' => 10,
    '/my_array/1' => 'green'
  }

This data can be manipulated with L<JSON::Schema::Modern::Utilities/jsonp_set>; it is also available
already populated into the instance data via L<JSON::Schema::Modern::Result/data>.

=head1 METHODS

=for Pod::Coverage BUILDARGS FREEZE THAW
METASCHEMA_URIS SPECIFICATION_VERSIONS_SUPPORTED SPECIFICATION_VERSION_DEFAULT

=head2 evaluate_json_string

  $result = $js->evaluate_json_string($data_as_json_string, $schema);
  $result = $js->evaluate_json_string($data_as_json_string, $schema, { collect_annotations => 1 });

Evaluates the provided instance data against the known schema document.

The data is in the form of a JSON-encoded string (in accordance with
L<RFC8259|https://datatracker.ietf.org/doc/html/rfc8259>). B<The string is expected to be UTF-8 encoded.>

The schema must be in one of these forms:

=over 4

=item *

a Perl data structure, such as what is returned from a JSON decode operation,

=item *

or a URI string indicating the identity of such a schema.

=back

Optionally, a hashref can be passed as a third parameter which allows changing the values of the
L</short_circuit>, L</collect_annotations>, L</scalarref_booleans>,
L</stringy_numbers>, L</strict>, L</with_defaults>, L</validate_formats>, and/or L</validate_content_schemas>
settings for just this evaluation call.

You can also pass use these keys to alter behaviour (these are generally only used by custom validation
applications that contain embedded JSON Schemas):

=over 4

=item *

C<data_path>: adjusts the effective path of the data instance as of the start of evaluation

=item *

C<traversed_keyword_path>: adjusts the accumulated path as of the start of evaluation (or last C<$id> or C<$ref>)

=item *

C<initial_schema_uri>: adjusts the recorded absolute keyword location of the start of evaluation

=back

The return value is a L<JSON::Schema::Modern::Result> object.

=head2 evaluate

  $result = $js->evaluate($instance_data, $schema);
  $result = $js->evaluate($instance_data, $schema, { short_circuit => 0 });

Evaluates the provided instance data against the known schema document.

The data is in the form of an unblessed nested Perl data structure representing any type that JSON
allows: null, boolean, string, number, object, array. (See L</Types> below.)

The schema must be in one of these forms:

=over 4

=item *

a Perl data structure, such as what is returned from a JSON decode operation

=item *

or a URI string (or L<Mojo::URL>) indicating the identity of such a schema.

=back

Optionally, a hashref can be passed as a third parameter which allows changing the values of the
L</short_circuit>, L</collect_annotations>, L</scalarref_booleans>,
L</stringy_numbers>, L</strict>, L</with_defaults>, L</validate_formats>, and/or L</validate_content_schemas>
settings for just this evaluation call.

You can also pass use these keys to alter behaviour (these are generally only used by custom validation
applications that contain embedded JSON Schemas):

=over 4

=item *

C<data_path>: adjusts the effective path of the data instance as of the start of evaluation

=item *

C<traversed_keyword_path>: adjusts the accumulated path as of the start of evaluation (or last C<$id> or C<$ref>)

=item *

C<callbacks>: see below

=back

You can pass a series of callback subs to this method, with the keys corresponding to keywords,
which is useful for
identifying various data that are not exposed by annotations.
This feature is experimental and may change in the future.

For example, to find the locations where all C<$ref> keywords are applied B<successfully>:

  my @used_ref_at;
  $js->evaluate($data, $schema_or_uri, {
    callbacks => {
      '$ref' => sub ($data, $schema, $state) {
        push @used_ref_at, $state->{data_path};
      }
    },
  });

Callbacks are not compatible with L</short_circuit> mode, as some keyword evaluations may be skipped.

The return value of C<evaluate> is a L<JSON::Schema::Modern::Result> object.

=head2 validate_schema

  $result = $js->validate_schema($schema);
  $result = $js->validate_schema($schema, $config_override);

Evaluates the provided schema as instance data against its metaschema. Accepts C<$schema> and
C<$config_override> parameters in the same form as L</evaluate>.

=head2 traverse

  $result = $js->traverse($schema);
  $result = $js->traverse($schema, { initial_schema_uri => 'http://example.com' });

Traverses the provided schema without evaluating it against any instance data. Returns the
internal state object accumulated during the traversal, including any identifiers found therein, and
any errors found during parsing. For internal purposes only.

Optionally, a hashref can be passed as a second parameter which alters some
behaviour (these are generally only used by custom validation
applications that contain embedded JSON Schemas):

=over 4

=item *

C<traversed_keyword_path>: adjusts the accumulated path as of the start of evaluation (or last C<$id> or C<$ref>)

=item *

C<initial_schema_uri>: adjusts the absolute keyword location as of the start of evaluation

=item *

C<metaschema_uri>: use the indicated URI as the metaschema

=item *

C<callbacks>: see below

=item *

C<specification_version>: overrides the specification version to be used

=back

You can pass a series of callback subs to this method corresponding to keywords, which is useful for
extracting data from within schemas and skipping properties that may look like keywords but actually
are not (for example C<{"const": {"$ref": "this is not actually a $ref"}}>). This feature is
experimental and is highly likely to change in the future.

For example, to find the resolved targets of all C<$ref> keywords in a schema document:

  my @refs;
  JSON::Schema::Modern->new->traverse($schema, {
    callbacks => {
      '$ref' => sub ($schema, $state) {
        push @refs, Mojo::URL->new($schema->{'$ref'})
          ->to_abs(JSON::Schema::Modern::Utilities::canonical_uri($state));
      }
    },
  });

=head2 add_schema

  $js->add_schema($uri => $schema);
  $js->add_schema($schema);

Introduces the (unblessed, nested) Perl data structure
representing a JSON Schema to the implementation, registering it under the indicated URI if
provided, and all identifiers found within the document will be resolved against this URI (if
provided) and added as well. C<''> will be used if no other identifier can be found within.

You B<MUST> call C<add_schema> or L</add_document> (below) for any external resources that a schema may reference via C<$ref>
before calling L</evaluate>, other than the standard metaschemas which are loaded from a local cache
as needed.

If you add multiple schemas (either with this method, or implicitly via L</evaluate>) with no root
identifier (either provided explicitly in the method call, or via an C<$id> keyword at the schema
root), all such previous schemas are removed from memory and can no longer be referenced.

If there were errors in the document, will die with these errors;
otherwise returns the L<JSON::Schema::Modern::Document> that contains the added schema. URIs
identified within this document will not be resolved to the provided C<$uri> argument, so you can
re-add the document object again (with L</add_document>, below) using a new base URI if you wish.

=head2 add_document

  $js->add_document($uri => $document);
  $js->add_document($document);

Makes the L<JSON::Schema::Modern::Document> (or subclass)
object, representing a JSON Schema, available to the evaluator. All identifiers known to the
document are added to the evaluator's resource index; if the C<$uri> argument is provided, those
identifiers are resolved against C<$uri> as they are added.

C<$uri> itself is also added to the resource index, referencing the root of the document itself.

If you add multiple documents (either with this method, or implicitly via C</add_schema> or L</evaluate>) with no root
identifier (either provided explicitly in the method call, or via an C<$id> keyword at the schema
root), all such previous schemas are removed from memory and can no longer be referenced.

If there were errors in the document, this method will die with these errors;
otherwise it returns the L<JSON::Schema::Modern::Document> object.

=head2 add_format_validation

  $js->add_format_validation(all_lc => sub ($value) { lc($value) eq $value });

=for comment we are the nine Eleven Deniers

or

  $js->add_format_validation(no_nines => { type => 'number', sub => sub ($value) { $value =~ m/^[0-8]+\z/ });

  $js->add_format_validation(8bits => { type => 'string', sub => sub ($value) { $value =~ m/^[\x00-\xFF]+\z/ });

Adds support for a custom format. If not supplied, the data type(s) that this format applies to
defaults to string; all values of any other type will automatically be deemed to be valid, and will
not be passed to the subref.

Additionally, you can redefine the definition for any core format (see L</Format Validation>), but
the data type(s) supported by that format may not be changed.

Be careful to not mutate the type of the value while checking it -- for example, if it is a string,
do not apply arithmetic operators to it -- or subsequent type checks on this value may fail.

See the official L<OpenAPI Format Registry|https://spec.openapis.org/registry/format>
for a registry of known and useful formats; for
compatibility reasons, avoid defining a format listed here with different semantics.

Format definitions cannot be overridden with a new definition.

=head2 add_vocabulary

  $js->add_vocabulary('My::Custom::Vocabulary::Class');

Makes a custom vocabulary class available to metaschemas that make use of this vocabulary.
as described in the specification at
L<"Meta-Schemas and Vocabularies"|https://json-schema.org/draft/2020-12/json-schema-core.html#rfc.section.8.1>.

The class must compose the L<JSON::Schema::Modern::Vocabulary> role and implement the
L<vocabulary|JSON::Schema::Modern::Vocabulary/vocabulary> and
L<keywords|JSON::Schema::Modern::Vocabulary/keywords> methods, as well as
C<< _traverse_keyword_<keyword name> >> methods for each keyword. C<< _eval_keyword_<keyword name> >>
methods are optional; when not provided, evaluation will always return a true result.

Vocabularies cannot be redefined; subsequent calls to add the same vocabulary will do nothing.

=head2 add_media_type

  $js->add_media_type('application/furble' => sub ($content_ref, @) {
    return ...;  # data representing the deserialized text for Content-Type: application/furble
  });

Takes a media-type name and a subref which takes a single scalar reference, which is expected to be
a reference to a string, which might contain wide characters (i.e. not octets), especially when used
in conjunction with L</get_encoding> below. Must return B<a reference to a value of any type> (which is
then dereferenced for the C<contentSchema> keyword).

This interface is B<deprecated> as of version 0.638 and may eventually be removed; use
L<JSON::Schema::Modern::Utilities/add_media_type> instead, which supports defining an encoder as
well, and supports media-type parameters.

=head2 get_media_type

  $js->add_media_type('application/furble' => sub { ... }); # as above
  my $decoder = $self->get_media_type('application/furble') or die 'cannot find media type decoder';
  my $content_ref = $decoder->(\$content_string);

Fetches a decoder sub from the current object's registry for the indicated media type. Lookups are
performed B<without case sensitivity>.

This interface is B<deprecated> as of version 0.638 and may eventually be removed; use
L<JSON::Schema::Modern::Utilities/decode_media_type> instead.

=head2 add_encoding

  $js->add_encoding('bloop' => sub ($content_ref, @) {
    return \ ...;  # data representing the deserialized content for Content-Transfer-Encoding: bloop
  });

Takes an encoding name and a subref which takes a single scalar reference, which is expected to be
a reference to a string, which SHOULD be a 7-bit or 8-bit string. Result values MUST be a scalar-reference
to a string (which is then dereferenced for the C<contentMediaType> keyword).

Encoding definitions can be overridden with a new call to C<add_encoding>.

=for stopwords natively

Encodings handled natively are:

=over 4

=item *

C<identity> - passes strings through unchanged

=item *

C<base64> - see L<RFC 4648 §4|https://datatracker.ietf.org/doc/html/rfc4648#section-4>

=item *

C<base64url> - see L<RFC 4648 §5|https://datatracker.ietf.org/doc/html/rfc4648#section-5>

=back

See also L<HTTP::Message/encode>.

=head2 get_encoding

  my $decoder = $self->get_encoding('base64') or die 'cannot find encoding decoder';
  my $content_ref = $decoder->(\$content_string);

Fetches a decoder sub for the indicated encoding. Incoming values MUST be a reference to an octet
string. Result values will be a scalar-reference to a string, which might be passed to a media_type
decoder (see above).

=head2 get

  my $schema = $js->get($uri);
  my ($schema, $canonical_uri) = $js->get($uri);

Fetches the Perl data structure represented by the indicated identifier (uri or
uri-reference). When called in list context, the canonical URI of that location is also returned, as
a L<Mojo::URL>. Returns C<undef> if the schema with that URI has not been loaded (or cached).

Note that the data so returned may not be a JSON Schema, if the document encapsulating this location
is a subclass of L<JSON::Schema::Modern::Document> (for example
L<JSON::Schema::Modern::Document::OpenAPI>, which contains addressable locations of various semantic
types).

=head2 get_document

  my $document = $js->get_document($uri_reference);

Fetches the L<JSON::Schema::Modern::Document> object (or subclass) that contains the provided
identifier (uri or uri-reference). C<undef> if the schema with that URI has not been loaded (or
cached).

Note: this _does not download a document from the network_. It only fetches the document from the
internal cache in the C<JSON::Schema::Modern> object.

=head1 CACHING

=for stopwords preforking

Very large documents, particularly those used by L<OpenAPI::Modern>, may take a noticeable time to be
loaded and parsed. You can reduce the impact to your preforking application by loading all necessary
documents at startup, and impact can be further reduced by saving objects to cache and then
reloading them (perhaps by using a timestamp or checksum to determine if a fresh reload is needed).

Custom L<format validations|/add_format_validation>, L<media types|/add_media_type> or
L<encodings|/add_encoding> are not serialized, as they are represented by subroutine references, and
will need to be manually added after thawing.

  sub get_evaluator (...) {
    my $serialized_file = path($filename);
    my $schema_file = path($schema_filename);
    my $js;
    if ($serialized_file->stat->mtime < $schema_file->stat->mtime)) {
      $js = JSON::Schema::Modern->new;
      $js->add_schema(decode_json($schema_file->slurp_raw));  # your application schema
      my $frozen = Sereal::Encoder->new({ freeze_callbacks => 1 })->encode($js);
      $serialized_file->spew_raw($frozen);
    }
    else {
      my $frozen = $serialized_file->slurp_raw;
      $js = Sereal::Decoder->new->decode($frozen);
    }

    # add custom format validations, media types and encodings here
    $js->add_media_type(...);

    return $js;
  }

See also L<OpenAPI::Modern/CACHING>.

=head1 LIMITATIONS

=head2 Types

Perl is a more loosely-typed language than JSON. This module delves into a value's internal
representation in an attempt to derive the true "intended" type of the value.
This should not be an issue if data validation is occurring
immediately after decoding a JSON payload, or if the JSON string itself is passed to this module.
If you are having difficulties, make sure you are using Perl's fastest and most trusted and
reliable JSON decoder, L<Cpanel::JSON::XS>.
Other JSON decoders are known to produce data with incorrect data types,
and data from other sources may also be problematic.

For more information, see L<Cpanel::JSON::XS/MAPPING>.

=head2 Format Validation

By default (and unless you specify a custom metaschema with the C<$schema> keyword or
L<JSON::Schema::Modern::Document/metaschema>),
formats are treated only as annotations, not assertions. When L</validate_formats> is
true, strings are also checked against the format as specified in the schema. At present the
following formats are supported for the latest version of the specification
(use of any other formats than these will always evaluate as true,
but remember you can always supply custom format handlers; see L</format_validations> above):

=over 4

=item *

C<date-time>

=item *

C<date>

=item *

C<time>

=item *

C<duration>

=item *

C<email>

=item *

C<idn-email>

=item *

C<hostname>

=item *

C<idn-hostname>

=item *

C<ipv4>

=item *

C<ipv6>

=item *

C<uri>

=item *

C<uri-reference>

=item *

C<iri>

=item *

C<uuid>

=item *

C<json-pointer>

=item *

C<relative-json-pointer>

=item *

C<regex>

=back

A few optional prerequisites are needed for some of these (if the prerequisite is missing,
validation will always succeed, unless draft2020-12 is in use with the Format-Assertion vocabulary
declared in the metaschema, in which case use of the format will produce an error).

=over 4

=item *

C<email> and C<idn-email> require L<Email::Address::XS> version 1.04 (or higher)

=item *

C<hostname> and C<idn-hostname> require L<Data::Validate::Domain> version 0.13 (or higher)

=item *

C<idn-hostname> also requires L<Net::IDN::Encode>

=item *

C<uri> requires L<Data::Validate::URI>

=back

=head2 Specification Compliance

This implementation is now fully specification-compliant (for versions
draft4, draft6, draft7, draft2019-09, draft2020-12).

However, some potentially-useful features are not yet implemented, such as:

=for stopwords Mojolicious

=over 4

=item *

loading schema documents from disk

=item *

loading schema documents from the network

=item *

loading schema documents from a local web application (e.g. L<Mojolicious>)

=item *

additional "official" output formats beyond C<flag>, C<basic>, and C<terse> (L<https://json-schema.org/draft/2020-12/json-schema-core.html#rfc.section.12>)

=back

=head1 SECURITY CONSIDERATIONS

The C<pattern> and C<patternProperties> keywords evaluate regular expressions from the schema,
the C<regex> format validator evaluates regular expressions from the data, and some keywords
in the Validation vocabulary perform floating point operations on potentially-very large numbers.
No effort is taken (at this time) to sanitize the regular expressions for embedded code or
detect potentially pathological constructs that may pose a security risk, either via denial of
service or by allowing exposure to the internals of your application. B<DO NOT USE SCHEMAS FROM
UNTRUSTED SOURCES.>

(In particular, see vulnerability
L<perl5363delta/CVE-2023-47038-Write-past-buffer-end-via-illegal-user-defined-Unicode-property>,
which was fixed in Perl releases 5.34.3, 5.36.3 and 5.38.1.)

=head1 BUNDLED META-SCHEMAS

These specification meta-schemas are bundled with this distribution and loaded as needed:

=over 4

=item *

C<http://json-schema.org/draft-04/schema#>

=item *

C<http://json-schema.org/draft-06/schema#>

=item *

C<http://json-schema.org/draft-07/schema#>

=item *

C<https://json-schema.org/draft/2019-09/schema>

=item *

C<https://json-schema.org/draft/2020-12/schema>

=back

=head1 SEE ALSO

=over 4

=item *

L<json-schema-eval>

=item *

L<https://json-schema.org>

=item *

L<RFC8259: The JavaScript Object Notation (JSON) Data Interchange Format|https://datatracker.ietf.org/doc/html/rfc8259>

=item *

L<RFC6901: JavaScript Object Notation (JSON) Pointer|https://datatracker.ietf.org/doc/html/rfc6901>

=item *

L<RFC3986: Uniform Resource Identifier (URI): Generic Syntax|https://datatracker.ietf.org/doc/html/rfc3986> dependencies and faster evaluation

=item *

L<https://json-schema.org/draft/2020-12>

=item *

L<https://json-schema.org/draft/2019-09>

=item *

L<https://json-schema.org/draft-07>

=item *

L<https://json-schema.org/draft-06>

=item *

L<https://json-schema.org/draft-04/draft-zyp-json-schema-04>

=item *

L<Understanding JSON Schema|https://json-schema.org/understanding-json-schema>: tutorial-focused documentation

=item *

L<Test::JSON::Schema>: test your data against a JSON Schema

=item *

L<Test::JSON::Schema::Acceptance>: contains the official JSON Schema test suite

=item *

L<JSON::Schema::Tiny>: a more stripped-down implementation of the specification, with fewer

=item *

L<OpenAPI::Modern>: a parser and evaluator for OpenAPI v3.1 documents

=item *

L<Mojolicious::Plugin::OpenAPI::Modern>: a Mojolicious plugin providing OpenAPI functionality

=item *

L<Test::Mojo::Role::OpenAPI::Modern>: test your Mojolicious application's OpenAPI compliance

=item *

L<https://spec.openapis.org/registry/format>

=item *

L<https://spec.openapis.org/registry/media-type>

=back

=head1 AVAILABILITY

This distribution and executable is available on modern Debian versions (via C<apt-get>) as the
C<libjson-schema-modern-perl> package.

=head1 GIVING THANKS

=for stopwords MetaCPAN GitHub

If you found this module to be useful, please show your appreciation by
adding a +1 in L<MetaCPAN|https://metacpan.org/dist/JSON-Schema-Modern>
and a star in L<GitHub|https://github.com/karenetheridge/JSON-Schema-Modern>.

=head1 SUPPORT

Bugs may be submitted through L<https://github.com/karenetheridge/JSON-Schema-Modern/issues>.

I am also usually active on irc, as 'ether' at C<irc.perl.org> and C<irc.libera.chat>.

=for stopwords OpenAPI

You can also find me on the L<JSON Schema Slack server|https://json-schema.slack.com> and L<OpenAPI Slack
server|https://open-api.slack.com>, which are also great resources for finding help.

=head1 AUTHOR

Karen Etheridge <ether@cpan.org>

=head1 COPYRIGHT AND LICENCE

This software is copyright (c) 2020 by Karen Etheridge.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

Some schema files have their own licence, in share/LICENSE.

=cut

Not written in Markdown, so it's shown here as plain text — view it formatted on GitHub.

Contributors

karenetheridge

1,737 commits

karenetheridge/JSON-Schema-Modern

Validate data against a schema using a JSON Schema

22

stars

1,737

commits

Perl

primary language

Sep 9, 2026

updated

metacpan.org/release/JSON-Schema-Modern/
json-schema

README

=pod

=encoding UTF-8

=for stopwords schema subschema metaschema validator evaluator OpenAPI

=head1 NAME

JSON::Schema::Modern - Validate data against a schema using a JSON Schema

=head1 VERSION

version 0.645

I use a linearly-increasing version numbering scheme. No meaning should be
presumed or inferred from the version being less than 1.0.

=head1 SYNOPSIS

  use JSON::Schema::Modern;

  $js = JSON::Schema::Modern->new(
    specification_version => 'draft2020-12',
    output_format => 'flag',
    ... # other options
  );
  $result = $js->evaluate($instance_data, $schema_data);

=head1 DESCRIPTION

This module is a fully-compliant L<JSON Schema|https://json-schema.org/> evaluator and
validator, targeting the currently-latest
L<Draft 2020-12|https://json-schema.org/specification-links.html#2020-12>
version of the specification.

=head1 CONSTRUCTOR ARGUMENTS

Unless otherwise noted, these are also available as read-only accessors.

=head2 specification_version

Indicates which version of the JSON Schema specification is used during evaluation. This value is
overridden by the value determined from the C<$schema> keyword in the schema used in evaluation
(when present), or defaults to the latest version (currently C<draft2020-12>).

The use of the C<$schema> keyword in your schema is I<HIGHLY> encouraged to ensure continued correct
operation of your schema. The current default value will not stay the same over time.

May be one of:

=over 4

=item *

L<C<draft2020-12> or C<2020-12>|https://json-schema.org/specification-links.html#2020-12>, corresponding to metaschema C<https://json-schema.org/draft/2020-12/schema>

=item *

L<C<draft2019-09> or C<2019-09>|https://json-schema.org/specification-links.html#2019-09-formerly-known-as-draft-8>, corresponding to metaschema C<https://json-schema.org/draft/2019-09/schema>

=item *

L<C<draft7> or C<7>|https://json-schema.org/specification-links.html#draft-7>, corresponding to metaschema C<http://json-schema.org/draft-07/schema#>

=item *

L<C<draft6> or C<6>|https://json-schema.org/specification-links.html#draft-6>, corresponding to metaschema C<http://json-schema.org/draft-06/schema#>

=item *

L<C<draft4> or C<4>|https://json-schema.org/specification-links.html#draft-4>, corresponding to metaschema C<http://json-schema.org/draft-04/schema#>

=back

=head2 output_format

One of: C<flag>, C<basic>, C<strict_basic>, C<terse>. Defaults to C<basic>.
C<strict_basic> can only be used with C<specification_version = draft2019-09>.
Passed to L<JSON::Schema::Modern::Result/output_format>.

=head2 short_circuit

When true, evaluation will return early in any execution path as soon as the outcome can be
determined, rather than continuing to find all errors or annotations.
This option is safe to use in all circumstances, even in the presence of
C<unevaluatedItems> and C<unevaluatedProperties> keywords: the validation result will not change;
only some errors will be omitted from the result.

Defaults to true when C<output_format> is C<flag>, and false otherwise.

=for Pod::Coverage max_traversal_depth

=head2 max_depth

The maximum number of levels deep a schema evaluation may go before evaluation is halted. This is to
protect against accidental infinite recursion, such as from two subschemas that each reference each
other, or badly-written schemas that could be optimized. Defaults to 50.

=head2 validate_formats

When true, the C<format> keyword will be treated as an assertion, not merely an annotation. Defaults
to true when specification_version is draft4, draft6 or draft7, and false for all other versions, but this may change in the future.

Note that the use of a format that does not have a defined handler will B<not> be interpreted as an
error in this mode; instead, the undefined format will simply be ignored. If you instead want this
to be treated as an evaluation error, you must define a custom schema dialect that uses the
format-assertion vocabulary (available in specification version C<draft2020-12>) and reference it in
your schema with the C<$schema> keyword.

=head2 format_validations

=for stopwords subref

An optional hashref that allows overriding the validation method for formats, or adding new ones.
Overrides to existing formats (see L</Format Validation>)
must be specified in the form of C<< { $format_name => $format_sub } >>, where
the format sub is a subref that takes one argument and returns a boolean result. New formats must
be specified in the form of C<< { $format_name => { type => $type, sub => $format_sub } } >>,
where the type indicates which of the data model types (null, object, array, boolean, string,
or number) the instance value must be for the format validation to be considered.

Not available as an accessor; see L</add_format_validation>.

=head2 validate_content_schemas

When true, the C<contentMediaType> and C<contentSchema> keywords are not treated as pure annotations:
C<contentEncoding> (when present) is used to decode the applied data payload and then
C<contentMediaType> will be used as the media-type for decoding to produce the data payload which is
then applied to the schema in C<contentSchema> for validation. (Note that treating these keywords as
anything beyond simple annotations is contrary to the specification, therefore this option defaults
to false.) The decoded data is also reflected in L<JSON::Schema::Modern::Result/data>.

See L</add_media_type> and L</add_encoding> for adding additional type support.

=for stopwords shhh

Technically only draft4, draft6 and draft7 allow this and drafts 2019-09 and 2020-12 prohibit ever returning the
subschema evaluation results together with their parent schema's results, so shhh. I'm trying to get this
fixed for the next draft.

=head2 collect_annotations

When true, annotations are collected from keywords that produce them, when validation succeeds.
These annotations are available in the returned result (see L<JSON::Schema::Modern::Result>).
Not operational when L</specification_version> is C<draft4>, C<draft6> or C<draft7>.

Defaults to false.

=head2 scalarref_booleans

When true, any value that is expected to be a boolean B<in the instance data> may also be provided
as the scalar references C<\0> or C<\1> (which are serialized as booleans by JSON backends).

Defaults to false.

=head2 stringy_numbers

When true, any value that is expected to be a number or integer B<in the instance data> may also be
expressed as a string. This applies only to the following keywords:

=over 4

=item *

C<type> (where both C<string> and C<number> (and possibly C<integer>) are considered valid)

=item *

C<const> and C<enum> (where the string C<"1"> will match with C<"const": 1>)

=item *

C<uniqueItems> (where strings and numbers are compared numerically to each other, if either or both are numeric)

=item *

C<multipleOf>

=item *

C<maximum>

=item *

C<exclusiveMaximum>

=item *

C<minimum>

=item *

C<exclusiveMinimum>

=item *

C<format> (for formats defined to validate numbers)

=back

This allows you to write a schema like this (which validates a string representing an integer):

  type: string
  pattern: ^[0-9]$
  multipleOf: 4
  minimum: 16
  maximum: 256

Such keywords are only applied if the value looks like a number, and do not generate a failure
otherwise. Values are determined to be numbers via L<perlapi/looks_like_number>.
This option is only intended to be used for evaluating data from sources that can only be strings,
such as the extracted value of an HTTP header or query parameter, or a value from an XML document.
In the OpenAPI context, it is preferable to use an explicit C<type> keyword in the schema to
indicate the value should be deserialized as a number).

Defaults to false.

=head2 strict

When true, unrecognized keywords are disallowed in schemas (they will cause an immediate abort
in L</traverse> or L</evaluate>), with the exception of keywords starting with C<x->. Note that
this option is expected to become the default behaviour in future versions of JSON Schema.

Defaults to false.

=head2 with_defaults

When true, for any property name referenced by a C<properties> keyword, or array item referenced
by a C<prefixItems> keyword (or the array form of C<items> in earlier specification versions), that
does not exist in the object currently being evaluated, will result in an entry being added to the
C<defaults> property in the result object (see L<JSON::Schema::Modern::Result/defaults>),
indicating that the application may wish to add this default value to their instance data.

Defaults data accumulated in subschemas that are subsequently determined to be invalid are
discarded, with the final results from all subschemas accumulated together in one hash.  No attempt
is made to resolve conflicting entries (last one wins).

For example, this data instance:

  {
    "my_object": {
      "alpha": 1,
      "gamma": 3
    },
    "my_array": [
      "yellow"
    ]
  }

evaluated against this schema:

  type: object
  properties:
    my_object:
      type: object
      properties:
        alpha:
          type: integer
          default: 10
        beta:
          type: integer
          default: 10
        gamma:
          type: integer
          default: 10
    my_array:
      type: array
      prefixItems:
        - type: string
          default: red
        - type: string
          default: green

will result in an C<defaults> entry of:

  {
    '/my_object/beta' => 10,
    '/my_array/1' => 'green'
  }

This data can be manipulated with L<JSON::Schema::Modern::Utilities/jsonp_set>; it is also available
already populated into the instance data via L<JSON::Schema::Modern::Result/data>.

=head1 METHODS

=for Pod::Coverage BUILDARGS FREEZE THAW
METASCHEMA_URIS SPECIFICATION_VERSIONS_SUPPORTED SPECIFICATION_VERSION_DEFAULT

=head2 evaluate_json_string

  $result = $js->evaluate_json_string($data_as_json_string, $schema);
  $result = $js->evaluate_json_string($data_as_json_string, $schema, { collect_annotations => 1 });

Evaluates the provided instance data against the known schema document.

The data is in the form of a JSON-encoded string (in accordance with
L<RFC8259|https://datatracker.ietf.org/doc/html/rfc8259>). B<The string is expected to be UTF-8 encoded.>

The schema must be in one of these forms:

=over 4

=item *

a Perl data structure, such as what is returned from a JSON decode operation,

=item *

or a URI string indicating the identity of such a schema.

=back

Optionally, a hashref can be passed as a third parameter which allows changing the values of the
L</short_circuit>, L</collect_annotations>, L</scalarref_booleans>,
L</stringy_numbers>, L</strict>, L</with_defaults>, L</validate_formats>, and/or L</validate_content_schemas>
settings for just this evaluation call.

You can also pass use these keys to alter behaviour (these are generally only used by custom validation
applications that contain embedded JSON Schemas):

=over 4

=item *

C<data_path>: adjusts the effective path of the data instance as of the start of evaluation

=item *

C<traversed_keyword_path>: adjusts the accumulated path as of the start of evaluation (or last C<$id> or C<$ref>)

=item *

C<initial_schema_uri>: adjusts the recorded absolute keyword location of the start of evaluation

=back

The return value is a L<JSON::Schema::Modern::Result> object.

=head2 evaluate

  $result = $js->evaluate($instance_data, $schema);
  $result = $js->evaluate($instance_data, $schema, { short_circuit => 0 });

Evaluates the provided instance data against the known schema document.

The data is in the form of an unblessed nested Perl data structure representing any type that JSON
allows: null, boolean, string, number, object, array. (See L</Types> below.)

The schema must be in one of these forms:

=over 4

=item *

a Perl data structure, such as what is returned from a JSON decode operation

=item *

or a URI string (or L<Mojo::URL>) indicating the identity of such a schema.

=back

Optionally, a hashref can be passed as a third parameter which allows changing the values of the
L</short_circuit>, L</collect_annotations>, L</scalarref_booleans>,
L</stringy_numbers>, L</strict>, L</with_defaults>, L</validate_formats>, and/or L</validate_content_schemas>
settings for just this evaluation call.

You can also pass use these keys to alter behaviour (these are generally only used by custom validation
applications that contain embedded JSON Schemas):

=over 4

=item *

C<data_path>: adjusts the effective path of the data instance as of the start of evaluation

=item *

C<traversed_keyword_path>: adjusts the accumulated path as of the start of evaluation (or last C<$id> or C<$ref>)

=item *

C<callbacks>: see below

=back

You can pass a series of callback subs to this method, with the keys corresponding to keywords,
which is useful for
identifying various data that are not exposed by annotations.
This feature is experimental and may change in the future.

For example, to find the locations where all C<$ref> keywords are applied B<successfully>:

  my @used_ref_at;
  $js->evaluate($data, $schema_or_uri, {
    callbacks => {
      '$ref' => sub ($data, $schema, $state) {
        push @used_ref_at, $state->{data_path};
      }
    },
  });

Callbacks are not compatible with L</short_circuit> mode, as some keyword evaluations may be skipped.

The return value of C<evaluate> is a L<JSON::Schema::Modern::Result> object.

=head2 validate_schema

  $result = $js->validate_schema($schema);
  $result = $js->validate_schema($schema, $config_override);

Evaluates the provided schema as instance data against its metaschema. Accepts C<$schema> and
C<$config_override> parameters in the same form as L</evaluate>.

=head2 traverse

  $result = $js->traverse($schema);
  $result = $js->traverse($schema, { initial_schema_uri => 'http://example.com' });

Traverses the provided schema without evaluating it against any instance data. Returns the
internal state object accumulated during the traversal, including any identifiers found therein, and
any errors found during parsing. For internal purposes only.

Optionally, a hashref can be passed as a second parameter which alters some
behaviour (these are generally only used by custom validation
applications that contain embedded JSON Schemas):

=over 4

=item *

C<traversed_keyword_path>: adjusts the accumulated path as of the start of evaluation (or last C<$id> or C<$ref>)

=item *

C<initial_schema_uri>: adjusts the absolute keyword location as of the start of evaluation

=item *

C<metaschema_uri>: use the indicated URI as the metaschema

=item *

C<callbacks>: see below

=item *

C<specification_version>: overrides the specification version to be used

=back

You can pass a series of callback subs to this method corresponding to keywords, which is useful for
extracting data from within schemas and skipping properties that may look like keywords but actually
are not (for example C<{"const": {"$ref": "this is not actually a $ref"}}>). This feature is
experimental and is highly likely to change in the future.

For example, to find the resolved targets of all C<$ref> keywords in a schema document:

  my @refs;
  JSON::Schema::Modern->new->traverse($schema, {
    callbacks => {
      '$ref' => sub ($schema, $state) {
        push @refs, Mojo::URL->new($schema->{'$ref'})
          ->to_abs(JSON::Schema::Modern::Utilities::canonical_uri($state));
      }
    },
  });

=head2 add_schema

  $js->add_schema($uri => $schema);
  $js->add_schema($schema);

Introduces the (unblessed, nested) Perl data structure
representing a JSON Schema to the implementation, registering it under the indicated URI if
provided, and all identifiers found within the document will be resolved against this URI (if
provided) and added as well. C<''> will be used if no other identifier can be found within.

You B<MUST> call C<add_schema> or L</add_document> (below) for any external resources that a schema may reference via C<$ref>
before calling L</evaluate>, other than the standard metaschemas which are loaded from a local cache
as needed.

If you add multiple schemas (either with this method, or implicitly via L</evaluate>) with no root
identifier (either provided explicitly in the method call, or via an C<$id> keyword at the schema
root), all such previous schemas are removed from memory and can no longer be referenced.

If there were errors in the document, will die with these errors;
otherwise returns the L<JSON::Schema::Modern::Document> that contains the added schema. URIs
identified within this document will not be resolved to the provided C<$uri> argument, so you can
re-add the document object again (with L</add_document>, below) using a new base URI if you wish.

=head2 add_document

  $js->add_document($uri => $document);
  $js->add_document($document);

Makes the L<JSON::Schema::Modern::Document> (or subclass)
object, representing a JSON Schema, available to the evaluator. All identifiers known to the
document are added to the evaluator's resource index; if the C<$uri> argument is provided, those
identifiers are resolved against C<$uri> as they are added.

C<$uri> itself is also added to the resource index, referencing the root of the document itself.

If you add multiple documents (either with this method, or implicitly via C</add_schema> or L</evaluate>) with no root
identifier (either provided explicitly in the method call, or via an C<$id> keyword at the schema
root), all such previous schemas are removed from memory and can no longer be referenced.

If there were errors in the document, this method will die with these errors;
otherwise it returns the L<JSON::Schema::Modern::Document> object.

=head2 add_format_validation

  $js->add_format_validation(all_lc => sub ($value) { lc($value) eq $value });

=for comment we are the nine Eleven Deniers

or

  $js->add_format_validation(no_nines => { type => 'number', sub => sub ($value) { $value =~ m/^[0-8]+\z/ });

  $js->add_format_validation(8bits => { type => 'string', sub => sub ($value) { $value =~ m/^[\x00-\xFF]+\z/ });

Adds support for a custom format. If not supplied, the data type(s) that this format applies to
defaults to string; all values of any other type will automatically be deemed to be valid, and will
not be passed to the subref.

Additionally, you can redefine the definition for any core format (see L</Format Validation>), but
the data type(s) supported by that format may not be changed.

Be careful to not mutate the type of the value while checking it -- for example, if it is a string,
do not apply arithmetic operators to it -- or subsequent type checks on this value may fail.

See the official L<OpenAPI Format Registry|https://spec.openapis.org/registry/format>
for a registry of known and useful formats; for
compatibility reasons, avoid defining a format listed here with different semantics.

Format definitions cannot be overridden with a new definition.

=head2 add_vocabulary

  $js->add_vocabulary('My::Custom::Vocabulary::Class');

Makes a custom vocabulary class available to metaschemas that make use of this vocabulary.
as described in the specification at
L<"Meta-Schemas and Vocabularies"|https://json-schema.org/draft/2020-12/json-schema-core.html#rfc.section.8.1>.

The class must compose the L<JSON::Schema::Modern::Vocabulary> role and implement the
L<vocabulary|JSON::Schema::Modern::Vocabulary/vocabulary> and
L<keywords|JSON::Schema::Modern::Vocabulary/keywords> methods, as well as
C<< _traverse_keyword_<keyword name> >> methods for each keyword. C<< _eval_keyword_<keyword name> >>
methods are optional; when not provided, evaluation will always return a true result.

Vocabularies cannot be redefined; subsequent calls to add the same vocabulary will do nothing.

=head2 add_media_type

  $js->add_media_type('application/furble' => sub ($content_ref, @) {
    return ...;  # data representing the deserialized text for Content-Type: application/furble
  });

Takes a media-type name and a subref which takes a single scalar reference, which is expected to be
a reference to a string, which might contain wide characters (i.e. not octets), especially when used
in conjunction with L</get_encoding> below. Must return B<a reference to a value of any type> (which is
then dereferenced for the C<contentSchema> keyword).

This interface is B<deprecated> as of version 0.638 and may eventually be removed; use
L<JSON::Schema::Modern::Utilities/add_media_type> instead, which supports defining an encoder as
well, and supports media-type parameters.

=head2 get_media_type

  $js->add_media_type('application/furble' => sub { ... }); # as above
  my $decoder = $self->get_media_type('application/furble') or die 'cannot find media type decoder';
  my $content_ref = $decoder->(\$content_string);

Fetches a decoder sub from the current object's registry for the indicated media type. Lookups are
performed B<without case sensitivity>.

This interface is B<deprecated> as of version 0.638 and may eventually be removed; use
L<JSON::Schema::Modern::Utilities/decode_media_type> instead.

=head2 add_encoding

  $js->add_encoding('bloop' => sub ($content_ref, @) {
    return \ ...;  # data representing the deserialized content for Content-Transfer-Encoding: bloop
  });

Takes an encoding name and a subref which takes a single scalar reference, which is expected to be
a reference to a string, which SHOULD be a 7-bit or 8-bit string. Result values MUST be a scalar-reference
to a string (which is then dereferenced for the C<contentMediaType> keyword).

Encoding definitions can be overridden with a new call to C<add_encoding>.

=for stopwords natively

Encodings handled natively are:

=over 4

=item *

C<identity> - passes strings through unchanged

=item *

C<base64> - see L<RFC 4648 §4|https://datatracker.ietf.org/doc/html/rfc4648#section-4>

=item *

C<base64url> - see L<RFC 4648 §5|https://datatracker.ietf.org/doc/html/rfc4648#section-5>

=back

See also L<HTTP::Message/encode>.

=head2 get_encoding

  my $decoder = $self->get_encoding('base64') or die 'cannot find encoding decoder';
  my $content_ref = $decoder->(\$content_string);

Fetches a decoder sub for the indicated encoding. Incoming values MUST be a reference to an octet
string. Result values will be a scalar-reference to a string, which might be passed to a media_type
decoder (see above).

=head2 get

  my $schema = $js->get($uri);
  my ($schema, $canonical_uri) = $js->get($uri);

Fetches the Perl data structure represented by the indicated identifier (uri or
uri-reference). When called in list context, the canonical URI of that location is also returned, as
a L<Mojo::URL>. Returns C<undef> if the schema with that URI has not been loaded (or cached).

Note that the data so returned may not be a JSON Schema, if the document encapsulating this location
is a subclass of L<JSON::Schema::Modern::Document> (for example
L<JSON::Schema::Modern::Document::OpenAPI>, which contains addressable locations of various semantic
types).

=head2 get_document

  my $document = $js->get_document($uri_reference);

Fetches the L<JSON::Schema::Modern::Document> object (or subclass) that contains the provided
identifier (uri or uri-reference). C<undef> if the schema with that URI has not been loaded (or
cached).

Note: this _does not download a document from the network_. It only fetches the document from the
internal cache in the C<JSON::Schema::Modern> object.

=head1 CACHING

=for stopwords preforking

Very large documents, particularly those used by L<OpenAPI::Modern>, may take a noticeable time to be
loaded and parsed. You can reduce the impact to your preforking application by loading all necessary
documents at startup, and impact can be further reduced by saving objects to cache and then
reloading them (perhaps by using a timestamp or checksum to determine if a fresh reload is needed).

Custom L<format validations|/add_format_validation>, L<media types|/add_media_type> or
L<encodings|/add_encoding> are not serialized, as they are represented by subroutine references, and
will need to be manually added after thawing.

  sub get_evaluator (...) {
    my $serialized_file = path($filename);
    my $schema_file = path($schema_filename);
    my $js;
    if ($serialized_file->stat->mtime < $schema_file->stat->mtime)) {
      $js = JSON::Schema::Modern->new;
      $js->add_schema(decode_json($schema_file->slurp_raw));  # your application schema
      my $frozen = Sereal::Encoder->new({ freeze_callbacks => 1 })->encode($js);
      $serialized_file->spew_raw($frozen);
    }
    else {
      my $frozen = $serialized_file->slurp_raw;
      $js = Sereal::Decoder->new->decode($frozen);
    }

    # add custom format validations, media types and encodings here
    $js->add_media_type(...);

    return $js;
  }

See also L<OpenAPI::Modern/CACHING>.

=head1 LIMITATIONS

=head2 Types

Perl is a more loosely-typed language than JSON. This module delves into a value's internal
representation in an attempt to derive the true "intended" type of the value.
This should not be an issue if data validation is occurring
immediately after decoding a JSON payload, or if the JSON string itself is passed to this module.
If you are having difficulties, make sure you are using Perl's fastest and most trusted and
reliable JSON decoder, L<Cpanel::JSON::XS>.
Other JSON decoders are known to produce data with incorrect data types,
and data from other sources may also be problematic.

For more information, see L<Cpanel::JSON::XS/MAPPING>.

=head2 Format Validation

By default (and unless you specify a custom metaschema with the C<$schema> keyword or
L<JSON::Schema::Modern::Document/metaschema>),
formats are treated only as annotations, not assertions. When L</validate_formats> is
true, strings are also checked against the format as specified in the schema. At present the
following formats are supported for the latest version of the specification
(use of any other formats than these will always evaluate as true,
but remember you can always supply custom format handlers; see L</format_validations> above):

=over 4

=item *

C<date-time>

=item *

C<date>

=item *

C<time>

=item *

C<duration>

=item *

C<email>

=item *

C<idn-email>

=item *

C<hostname>

=item *

C<idn-hostname>

=item *

C<ipv4>

=item *

C<ipv6>

=item *

C<uri>

=item *

C<uri-reference>

=item *

C<iri>

=item *

C<uuid>

=item *

C<json-pointer>

=item *

C<relative-json-pointer>

=item *

C<regex>

=back

A few optional prerequisites are needed for some of these (if the prerequisite is missing,
validation will always succeed, unless draft2020-12 is in use with the Format-Assertion vocabulary
declared in the metaschema, in which case use of the format will produce an error).

=over 4

=item *

C<email> and C<idn-email> require L<Email::Address::XS> version 1.04 (or higher)

=item *

C<hostname> and C<idn-hostname> require L<Data::Validate::Domain> version 0.13 (or higher)

=item *

C<idn-hostname> also requires L<Net::IDN::Encode>

=item *

C<uri> requires L<Data::Validate::URI>

=back

=head2 Specification Compliance

This implementation is now fully specification-compliant (for versions
draft4, draft6, draft7, draft2019-09, draft2020-12).

However, some potentially-useful features are not yet implemented, such as:

=for stopwords Mojolicious

=over 4

=item *

loading schema documents from disk

=item *

loading schema documents from the network

=item *

loading schema documents from a local web application (e.g. L<Mojolicious>)

=item *

additional "official" output formats beyond C<flag>, C<basic>, and C<terse> (L<https://json-schema.org/draft/2020-12/json-schema-core.html#rfc.section.12>)

=back

=head1 SECURITY CONSIDERATIONS

The C<pattern> and C<patternProperties> keywords evaluate regular expressions from the schema,
the C<regex> format validator evaluates regular expressions from the data, and some keywords
in the Validation vocabulary perform floating point operations on potentially-very large numbers.
No effort is taken (at this time) to sanitize the regular expressions for embedded code or
detect potentially pathological constructs that may pose a security risk, either via denial of
service or by allowing exposure to the internals of your application. B<DO NOT USE SCHEMAS FROM
UNTRUSTED SOURCES.>

(In particular, see vulnerability
L<perl5363delta/CVE-2023-47038-Write-past-buffer-end-via-illegal-user-defined-Unicode-property>,
which was fixed in Perl releases 5.34.3, 5.36.3 and 5.38.1.)

=head1 BUNDLED META-SCHEMAS

These specification meta-schemas are bundled with this distribution and loaded as needed:

=over 4

=item *

C<http://json-schema.org/draft-04/schema#>

=item *

C<http://json-schema.org/draft-06/schema#>

=item *

C<http://json-schema.org/draft-07/schema#>

=item *

C<https://json-schema.org/draft/2019-09/schema>

=item *

C<https://json-schema.org/draft/2020-12/schema>

=back

=head1 SEE ALSO

=over 4

=item *

L<json-schema-eval>

=item *

L<https://json-schema.org>

=item *

L<RFC8259: The JavaScript Object Notation (JSON) Data Interchange Format|https://datatracker.ietf.org/doc/html/rfc8259>

=item *

L<RFC6901: JavaScript Object Notation (JSON) Pointer|https://datatracker.ietf.org/doc/html/rfc6901>

=item *

L<RFC3986: Uniform Resource Identifier (URI): Generic Syntax|https://datatracker.ietf.org/doc/html/rfc3986> dependencies and faster evaluation

=item *

L<https://json-schema.org/draft/2020-12>

=item *

L<https://json-schema.org/draft/2019-09>

=item *

L<https://json-schema.org/draft-07>

=item *

L<https://json-schema.org/draft-06>

=item *

L<https://json-schema.org/draft-04/draft-zyp-json-schema-04>

=item *

L<Understanding JSON Schema|https://json-schema.org/understanding-json-schema>: tutorial-focused documentation

=item *

L<Test::JSON::Schema>: test your data against a JSON Schema

=item *

L<Test::JSON::Schema::Acceptance>: contains the official JSON Schema test suite

=item *

L<JSON::Schema::Tiny>: a more stripped-down implementation of the specification, with fewer

=item *

L<OpenAPI::Modern>: a parser and evaluator for OpenAPI v3.1 documents

=item *

L<Mojolicious::Plugin::OpenAPI::Modern>: a Mojolicious plugin providing OpenAPI functionality

=item *

L<Test::Mojo::Role::OpenAPI::Modern>: test your Mojolicious application's OpenAPI compliance

=item *

L<https://spec.openapis.org/registry/format>

=item *

L<https://spec.openapis.org/registry/media-type>

=back

=head1 AVAILABILITY

This distribution and executable is available on modern Debian versions (via C<apt-get>) as the
C<libjson-schema-modern-perl> package.

=head1 GIVING THANKS

=for stopwords MetaCPAN GitHub

If you found this module to be useful, please show your appreciation by
adding a +1 in L<MetaCPAN|https://metacpan.org/dist/JSON-Schema-Modern>
and a star in L<GitHub|https://github.com/karenetheridge/JSON-Schema-Modern>.

=head1 SUPPORT

Bugs may be submitted through L<https://github.com/karenetheridge/JSON-Schema-Modern/issues>.

I am also usually active on irc, as 'ether' at C<irc.perl.org> and C<irc.libera.chat>.

=for stopwords OpenAPI

You can also find me on the L<JSON Schema Slack server|https://json-schema.slack.com> and L<OpenAPI Slack
server|https://open-api.slack.com>, which are also great resources for finding help.

=head1 AUTHOR

Karen Etheridge <ether@cpan.org>

=head1 COPYRIGHT AND LICENCE

This software is copyright (c) 2020 by Karen Etheridge.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

Some schema files have their own licence, in share/LICENSE.

=cut

Not written in Markdown, so it's shown here as plain text — view it formatted on GitHub.

Contributors

karenetheridge

1,737 commits

Languages

Perl

100.0%