JSON::Validator - Validate data against a JSON schema
2.06
use JSON::Validator;
my $validator = JSON::Validator->new;
# Define a schema - http://json-schema.org/examples.html
# You can also load schema from disk or web
$validator->schema(
{
type => "object",
required => ["firstName", "lastName"],
properties => {
firstName => {type => "string"},
lastName => {type => "string"},
age => {type => "integer", minimum => 0, description => "Age in years"}
}
}
);
# Validate your data
@errors = $validator->validate({firstName => "Jan Henning", lastName => "Thorsen", age => -42});
# Do something if any errors was found
die "@errors" if @errors;
JSON::Validator is a class for validating data against JSON schemas. You might want to use this instead of JSON::Schema if you need to validate data against draft 4 of the specification.
This module can be used standalone, but if you want to define a specification for your webserver's API, then have a look at Mojolicious::Plugin::OpenAPI, which will replace Mojolicious::Plugin::Swagger2.
JSON::Validator can load JSON schemas in multiple formats: Plain perl data structured (as shown in "SYNOPSIS"), JSON or YAML. The JSON parsing is done with Mojo::JSON, while YAML files require the optional module YAML::XS to be installed.
IMPORTANT! YAML::Syck is not supported in JSON::Validator 2.00. Only YAML::XS is supported, since it has proper boolean handling. Look for $YAML::XS::Boolean
in the documentation to see what is recognized as booleans.
Here are some resources that are related to JSON schemas and validation:
This module comes with some JSON specifications bundled, so your application don't have to fetch those from the web. These specifications should be up to date, but please submit an issue if they are not.
Files referenced to an URL will automatically be cached if the first element in "cache_paths" is a writable directory. Note that the cache headers for the remote assets are not honored, so you will manually need to remove any cached file, should you need to refresh them.
To download and cache an online asset, do this:
JSON_VALIDATOR_CACHE_PATH=/some/writable/directory perl myapp.pl
Here is the list of the bundled specifications:
JSON schema, draft 4
Web page: http://json-schema.org
JSON schema for JSONPatch files
Web page: http://jsonpatch.com
Swagger / OpenAPI specification, version 2
Web page: https://openapis.org
Custom error document
There is a custom schema used by Mojolicious::Plugin::OpenAPI as a default error document. This document might be extended later, but it will always be backward compatible.
Specification: https://github.com/jhthorsen/json-validator/blob/master/lib/JSON/Validator/cache/630949337805585c8e52deea27d11419
$ref
: http://git.io/vcKD4#.Swagger Petstore
This is used for unit tests, and should probably not be relied on by external users.
The method "validate" and the function "validate_json" returns error objects when the input data violates the "schema". Each of the objects looks like this:
bless {
message => "Some description",
path => "/json/path/to/node",
}, "JSON::Validator::Error"
See also JSON::Validator::Error.
The error object overloads the following operators:
bool
Returns a true value.
string
Returns the "path" and "message" part as a string: "$path: $message".
Have a look at the test suite for documented examples of the error cases. Especially look at jv-allof.t
, jv-anyof.t
and jv-oneof.t
.
The special cases for "allOf", "anyOf" and "oneOf" will contain the error messages from all the failing rules below. It can be a bit hard to read, so if the error message is long, then you might want to run a smaller test with JSON_VALIDATOR_DEBUG=1
.
Example error object:
bless {
message => "(String is too long: 8/5. String is too short: 8/12)",
path => "/json/path/to/node",
}, "JSON::Validator::Error"
Note that these error messages are subject for change. Any suggestions are most welcome!
use JSON::Validator "joi";
my $joi = joi;
my @errors = joi($data, $joi); # same as $joi->validate($data);
Used to construct a new JSON::Validator::Joi object or perform validation.
Note that this function iS EXPERIMENTAL. See JSON::Validator::Joi for more details.
use JSON::Validator "validate_json";
@errors = validate_json $data, $schema;
This can be useful in web applications:
@errors = validate_json $c->req->json, "data://main/spec.json";
See also "validate" and "ERROR OBJECT" for more details.
$self = $self->cache_paths(\@paths);
$array_ref = $self->cache_paths;
A list of directories to where cached specifications are stored. Defaults to JSON_VALIDATOR_CACHE_PATH
environment variable and the specs that is bundled with this distribution.
JSON_VALIDATOR_CACHE_PATH
can be a list of directories, each separated by ":".
See "Bundled specifications" for more details.
$hash_ref = $self->formats;
$self = $self->formats(\%hash);
Holds a hash-ref, where the keys are supported JSON type "formats", and the values holds a code block which can validate a given format.
Note! The modules mentioned below are optional.
date-time
An RFC3339 timestamp in UTC time. This is formatted as "YYYY-MM-DDThh:mm:ss.fffZ". The milliseconds portion (".fff") is optional
email
Validated against the RFC5322 spec.
hostname
Will be validated using Data::Validate::Domain if installed.
ipv4
Will be validated using Data::Validate::IP if installed or fall back to a plain IPv4 IP regex.
ipv6
Will be validated using Data::Validate::IP if installed.
regex
EXPERIMENTAL. Will check if the string is a regex, using
qr{...}
.uri
Validated against the RFC3986 spec.
$ua = $self->ua;
$self = $self->ua(Mojo::UserAgent->new);
Holds a Mojo::UserAgent object, used by "schema" to load a JSON schema from remote location.
Note that the default Mojo::UserAgent will detect proxy settings and have "max_redirects" in Mojo::UserAgent set to 3. (These settings are EXPERIMENTAL and might change without a warning)
$schema = $self->bundle(\%args);
Used to create a new schema, where the $ref
are resolved. %args
can have:
{replace =
1}>Used if you want to replace the
$ref
inline in the schema. This currently does not work if you have circular references. The default is to move all the$ref
definitions into the main schema with custom names. Here is an example on how a$ref
looks before and after:{"$ref":"../some/place.json#/foo/bar"} => {"$ref":"#/definitions/____some_place_json-_foo_bar"} {"$ref":"http://example.com#/foo/bar"} => {"$ref":"#/definitions/_http___example_com-_foo_bar"}
{schema =
{...}}>Default is to use the value from the "schema" attribute.
$self = $self->coerce(booleans => 1, numbers => 1, strings => 1);
$self = $self->coerce({booleans => 1, numbers => 1, strings => 1});
$hash = $self->coerce;
Set the given type to coerce. Before enabling coercion this module is very strict when it comes to validating types. Example: The string "1"
is not the same as the number 1
, unless you have coercion enabled.
Loading a YAML document will enable "booleans" automatically. This feature is experimental, but was added since YAML has no real concept of booleans, such as Mojo::JSON or other JSON parsers.
The coercion rules are EXPERIMENTAL and will be tighten/loosen if bugs are reported. See jhthorsen#8 for more details.
$sub_schema = $self->get("/x/y");
$sub_schema = $self->get(["x", "y"]);
Extract value from "schema" identified by the given JSON Pointer. Will at the same time resolve $ref
if found. Example:
$self->schema({x => {'$ref' => '#/y'}, y => {'type' => 'string'}});
$self->schema->get('/x') == undef
$self->schema->get('/x')->{'$ref'} == '#/y'
$self->get('/x') == {type => 'string'}
This method is EXPERIMENTAL.
The argument can also be an array-ref with the different parts of the pointer as each elements.
$self = $self->load_and_validate_schema($schema, \%args);
Will load and validate $schema
against the OpenAPI specification. $schema
can be anything "schema" in JSON::Validator accepts. The expanded specification will be stored in "schema" in JSON::Validator on success. See "schema" in JSON::Validator for the different version of $url
that can be accepted.
%args
can be used to further instruct the validation process:
schema
Defaults to "http://json-schema.org/draft-04/schema#", but can be any structured that can be used to validate
$schema
.
$self = $self->schema($json_or_yaml_string);
$self = $self->schema($url);
$self = $self->schema(\%schema);
$schema = $self->schema;
Used to set a schema from either a data structure or a URL.
$schema
will be a Mojo::JSON::Pointer object when loaded, and undef
by default.
The $url
can take many forms, but needs to point to a text file in the JSON or YAML format.
http://... or https://...
A web resource will be fetched using the Mojo::UserAgent, stored in "ua".
data://Some::Module/file.name
This version will use "data_section" in Mojo::Loader to load "file.name" from the module "Some::Module".
/path/to/file
An URL (without a recognized scheme) will be loaded from disk.
$self = $class->singleton;
Returns the JSON::Validator object used by "validate_json".
@errors = $self->validate($data);
@errors = $self->validate($data, $schema);
Validates $data
against a given JSON "schema". @errors
will contain validation error objects or be an empty list on success.
See "ERROR OBJECT" for details.
$schema
is optional, but when specified, it will override schema stored in "schema". Example:
$self->validate({hero => "superwoman"}, {type => "object"});
Copyright (C) 2014-2015, Jan Henning Thorsen
This program is free software, you can redistribute it and/or modify it under the terms of the Artistic License version 2.0.
Jan Henning Thorsen - jhthorsen@cpan.org
Daniel Böhmer - post@daniel-boehmer.de
Kevin Goess - cpan@goess.org
Martin Renvoize - martin.renvoize@gmail.com