Skip site navigation (1)Skip section navigation (2)

FreeBSD Manual Pages

  
 
  

home | help
JSON::Validator(3)    User Contributed Perl Documentation   JSON::Validator(3)

NAME
       JSON::Validator - Validate data against a JSON schema

SYNOPSIS
   Using a schema object
       JSON::Validator::Schema or any of the sub classes can be	used instead
       of JSON::Validator.

   Basics
	 use JSON::Validator;
	 my $jv	= JSON::Validator->new;

	 # Define a schema - http://json-schema.org/learn/miscellaneous-examples.html
	 # You can also	load schema from disk or web
	 $jv->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
	 my @errors = $jv->validate({firstName => "Jan Henning", lastName => "Thorsen",	age => -42});

	 # Do something	if any errors was found
	 die "@errors" if @errors;

   Using joi
	 # Use joi() to	build the schema
	 use JSON::Validator::Joi 'joi';

	 $jv->schema(joi->object->props({
	   firstName =>	joi->string->required,
	   lastName  =>	joi->string->required,
	   age	     =>	joi->integer->min(0),
	 }));

	 # joi() can also validate directly
	 my @errors = joi(
	   {firstName => "Jan Henning",	lastName => "Thorsen", age => -42},
	   joi->object->props({
	     firstName => joi->string->required,
	     lastName  => joi->string->required,
	     age       => joi->integer->min(0),
	   }),
	 );

DESCRIPTION
       JSON::Validator is a data structure validation library based around
       JSON Schema <https://json-schema.org/>. This module can be used
       directly	with a JSON schema or you can use the elegant DSL schema-
       builder JSON::Validator::Joi to define the schema programmatically.

   Supported schema formats
       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 requires YAML::PP or
       YAML::XS.

   Resources
       Here are	some resources that are	related	to JSON	schemas	and
       validation:

       o   <http://json-schema.org/documentation.html>

       o   <https://json-schema.org/understanding-json-schema/index.html>

       o   <https://github.com/json-schema/json-schema/>

   Bundled specifications
       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:

       o JSON schema, draft 4, 6, 7, 2019-09.

	 Web page: <http://json-schema.org>

	 $ref: <http://json-schema.org/draft-04/schema#>,
	 <http://json-schema.org/draft-06/schema#>,
	 <http://json-schema.org/draft-07/schema#>.

       o JSON schema for JSONPatch files

	 Web page: <http://jsonpatch.com>

	 $ref: <http://json.schemastore.org/json-patch#>

       o Swagger / OpenAPI specification, version 2

	 Web page: <https://openapis.org>

	 $ref: <http://swagger.io/v2/schema.json#>

       o OpenAPI specification,	version	3

	 Web page: <https://openapis.org>

	 $ref: https://spec.openapis.org/oas/3.0/schema/2019-04-02
	 <https://github.com/OAI/OpenAPI-
	 Specification/blob/master/schemas/v3.0/schema.json>

	 This specification is still EXPERIMENTAL.

       o Swagger Petstore

	 This is used for unit tests, and should not be	relied on by external
	 users.

   Optional modules
       o Sereal::Encoder

	 Installing Sereal::Encoder v4.00 (or later) will make "data_checksum"
	 in JSON::Validator::Util significantly	faster.	This function is used
	 both when parsing schemas and validating data.

       o Format	validators

	 See the documentation in JSON::Validator::Formats for other optional
	 modules to do validation of specific "format",	such as	"hostname",
	 "ipv4"	and others.

ERROR OBJECT
       The method "validate" returns a list of JSON::Validator::Error objects
       when the	input data violates the	"schema".

ATTRIBUTES
   cache_paths
       Proxy attribute for "cache_paths" in JSON::Validator::Store.

   formats
	 my $hash_ref =	$jv->formats;
	 my $jv	= $jv->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.	A code
       block should return "undef" on success and an error string on error:

	 sub { return defined $_[0] && $_[0] eq	"42" ? undef : "Not the	answer." };

       See JSON::Validator::Formats for	a list of supported formats.

   recursive_data_protection
	 my $jv	= $jv->recursive_data_protection($bool);
	 my $bool = $jv->recursive_data_protection;

       Recursive data protection is active by default, however it can be
       deactivated by assigning	a false	value to the
       "recursive_data_protection" attribute.

       Recursive data protection can have a noticeable impact on memory	usage
       when validating large data structures. If you are encountering issues
       with memory and you can guarantee that you do not have any loops	in
       your data structure then	deactivating the recursive data	protection may
       help.

       This attribute is EXPERIMENTAL and may change in	a future release.

       Disclaimer: Use at your own risk, if you	have any doubt then don't use
       it

   store
	 $store	= $jv->store;

       Holds a JSON::Validator::Store object that caches the retrieved
       schemas.	 This object can be shared amongst different schema objects to
       prevent a schema	from having to be downloaded again.

   ua
       Proxy attribute for "ua"	in JSON::Validator::Store.

METHODS
   bundle
	 # These two lines does	the same
	 my $schema = $jv->bundle({schema => $jv->schema->data});
	 my $schema = $jv->bundle;

	 # Will	only bundle a section of the schema
	 my $schema = $jv->bundle({schema => $jv->schema->get("/properties/person/age")});

       Used to create a	new schema, where there	are no "$ref" pointing to
       external	resources. This	means that all the "$ref" that are found, will
       be moved	into the "definitions" key, in the returned $schema.

   coerce
	 my $jv	      =	$jv->coerce('bool,def,num,str');
	 my $jv	      =	$jv->coerce('booleans,defaults,numbers,strings');
	 my $hash_ref =	$jv->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	"numbers" coercion
       enabled.

       o booleans

	 Will convert what looks can be	interpreted as a boolean (that is, an
	 actual	numeric	1 or 0,	and the	strings	"true" and "false") to a
	 JSON::PP::Boolean object. Note	that "foo" is not considered a true
	 value and will	fail the validation.

       o defaults

	 Will copy the default value defined in	the schema, into the input
	 structure, if the input value is non-existing.

	 Note that support for "default" is currently EXPERIMENTAL, and
	 enabling this might be	changed	in future versions.

       o numbers

	 Will convert strings that looks like numbers, into true numbers. This
	 works for both	the "integer" and "number" types.

       o strings

	 Will convert a	number into a string. This works for the "string"
	 type.

   get
	 my $sub_schema	= $jv->get("/x/y");
	 my $sub_schema	= $jv->get(["x", "y"]);

       Extract value from "schema" identified by the given JSON	Pointer. Will
       at the same time	resolve	$ref if	found. Example:

	 $jv->schema({x	=> {'$ref' => '#/y'}, y	=> {'type' => 'string'}});
	 $jv->schema->get('/x')		  == {'$ref' =>	'#/y'}
	 $jv->schema->get('/x')->{'$ref'} == '#/y'
	 $jv->get('/x')			  == {type => 'string'}

       The argument can	also be	an array-ref with the different	parts of the
       pointer as each elements.

   new
	 $jv = JSON::Validator->new(%attributes);
	 $jv = JSON::Validator->new(\%attributes);

       Creates a new JSON::Validate object.

   load_and_validate_schema
	 my $jv	= $jv->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:

       o schema

	 Defaults to "http://json-schema.org/draft-04/schema#",	but can	be any
	 structured that can be	used to	validate $schema.

   schema
	 my $jv	    = $jv->schema($json_or_yaml_string);
	 my $jv	    = $jv->schema($url);
	 my $jv	    = $jv->schema(\%schema);
	 my $jv	    = $jv->schema(JSON::Validator::Joi->new);
	 my $jv	    = $jv->schema(JSON::Validator::Schema->new);
	 my $schema = $jv->schema;

       Used to set a schema from either	a data structure or a URL.

       $schema will be a JSON::Validator::Schema 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.

       o   file://...

	   A file on disk. Note	that it	is required to use the "file" scheme
	   if you want to reference absolute paths on your file	system.

       o   http://... or https://...

	   A web resource will be fetched using	the Mojo::UserAgent, stored in
	   "ua".

       o   data://Some::Module/spec.json

	   Will	load a given "spec.json" file from "Some::Module" using
	   "data_section" in JSON::Validator::Util.

       o   data:///spec.json

	   A "data" URL	without	a module name will use the current package and
	   search up the call/inheritance tree.

       o   Any other URL

	   An URL (without a recognized	scheme)	will be	treated	as a path to a
	   file	on disk. If the	file could not be found	on disk	and the	path
	   starts with "/", then the will be loaded from the app defined in
	   "ua". Something like	this:

	     $jv->ua->server->app(MyMojoApp->new);
	     $jv->ua->get('/any/other/url.json');

   validate
	 my @errors = $jv->validate($data);

       Validates $data against "schema". @errors will contain validation error
       objects,	in a predictable order (specifically, alphanumerically sorted
       by the error objects' "path") or	be an empty list on success.

       See "ERROR OBJECT" for details.

SEE ALSO
       o JSON::Validator::Formats

	 JSON::Validator::Formats contains utility functions for validating
	 data types. Could be useful for validating data without loading a
	 schema.

       o JSON::Validator::Schema

	 JSON::Validator::Schema is the	base class for
	 JSON::Validator::Schema::Draft4, JSON::Validator::Schema::Draft6
	 JSON::Validator::Schema::Draft7,
	 JSON::Validator::Schema::Draft201909,
	 JSON::Validator::Schema::OpenAPIv2 or
	 JSON::Validator::Schema::OpenAPIv3.

       o JSON::Validator::Util

	 JSON::Validator::Util contains	many useful function when working with
	 schemas.

       o Mojolicious::Plugin::OpenAPI

	 Mojolicious::Plugin::OpenAPI is a plugin for Mojolicious that utilize
	 JSON::Validator and the OpenAPI specification
	 <https://www.openapis.org/> to	build routes with input	and output
	 validation.

COPYRIGHT AND LICENSE
       Copyright (C) 2014-2021,	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.

AUTHOR
       Jan Henning Thorsen - "jhthorsen@cpan.org"

       Daniel BA<paragraph>hmer	- "post@daniel-boehmer.de"

       Ed J - "mohawk2@users.noreply.github.com"

       Karen Etheridge - "ether@cpan.org"

       Kevin Goess - "cpan@goess.org"

       Martin Renvoize - "martin.renvoize@gmail.com"

perl v5.32.1			  2021-06-18		    JSON::Validator(3)

NAME | SYNOPSIS | DESCRIPTION | ERROR OBJECT | ATTRIBUTES | METHODS | SEE ALSO | COPYRIGHT AND LICENSE | AUTHOR

Want to link to this manual page? Use this URL:
<https://www.freebsd.org/cgi/man.cgi?query=JSON::Validator&sektion=3&manpath=FreeBSD+13.0-RELEASE+and+Ports>

home | help