1JSON::Validator(3)    User Contributed Perl Documentation   JSON::Validator(3)
2
3
4

NAME

6       JSON::Validator - Validate data against a JSON schema
7

SYNOPSIS

9   Using a schema object
10       JSON::Validator::Schema or any of the sub classes can be used instead
11       of JSON::Validator.
12
13   Basics
14         use JSON::Validator;
15         my $jv = JSON::Validator->new;
16
17         # Define a schema - http://json-schema.org/learn/miscellaneous-examples.html
18         # You can also load schema from disk or web
19         $jv->schema({
20           type       => "object",
21           required   => ["firstName", "lastName"],
22           properties => {
23             firstName => {type => "string"},
24             lastName  => {type => "string"},
25             age       => {type => "integer", minimum => 0, description => "Age in years"}
26           }
27         });
28
29         # Validate your data
30         my @errors = $jv->validate({firstName => "Jan Henning", lastName => "Thorsen", age => -42});
31
32         # Do something if any errors was found
33         die "@errors" if @errors;
34
35   Using joi
36         # Use joi() to build the schema
37         use JSON::Validator::Joi 'joi';
38
39         $jv->schema(joi->object->props({
40           firstName => joi->string->required,
41           lastName  => joi->string->required,
42           age       => joi->integer->min(0),
43         }));
44
45         # joi() can also validate directly
46         my @errors = joi(
47           {firstName => "Jan Henning", lastName => "Thorsen", age => -42},
48           joi->object->props({
49             firstName => joi->string->required,
50             lastName  => joi->string->required,
51             age       => joi->integer->min(0),
52           }),
53         );
54

DESCRIPTION

56       JSON::Validator is a data structure validation library based around
57       JSON Schema <https://json-schema.org/>. This module can be used
58       directly with a JSON schema or you can use the elegant DSL schema-
59       builder JSON::Validator::Joi to define the schema programmatically.
60
61   Supported schema formats
62       JSON::Validator can load JSON schemas in multiple formats: Plain perl
63       data structured (as shown in "SYNOPSIS"), JSON or YAML. The JSON
64       parsing is done with Mojo::JSON, while YAML files requires YAML::PP or
65       YAML::XS.
66
67   Resources
68       Here are some resources that are related to JSON schemas and
69       validation:
70
71       •   <http://json-schema.org/documentation.html>
72
73       •   <https://json-schema.org/understanding-json-schema/index.html>
74
75       •   <https://github.com/json-schema/json-schema/>
76
77   Bundled specifications
78       This module comes with some JSON specifications bundled, so your
79       application don't have to fetch those from the web. These
80       specifications should be up to date, but please submit an issue if they
81       are not.
82
83       Files referenced to an URL will automatically be cached if the first
84       element in "cache_paths" is a writable directory. Note that the cache
85       headers for the remote assets are not honored, so you will manually
86       need to remove any cached file, should you need to refresh them.
87
88       To download and cache an online asset, do this:
89
90         JSON_VALIDATOR_CACHE_PATH=/some/writable/directory perl myapp.pl
91
92       Here is the list of the bundled specifications:
93
94       • JSON schema, draft 4, 6, 7, 2019-09.
95
96         Web page: <http://json-schema.org>
97
98         $ref: <http://json-schema.org/draft-04/schema#>,
99         <http://json-schema.org/draft-06/schema#>,
100         <http://json-schema.org/draft-07/schema#>.
101
102       • JSON schema for JSONPatch files
103
104         Web page: <http://jsonpatch.com>
105
106         $ref: <http://json.schemastore.org/json-patch#>
107
108       • Swagger / OpenAPI specification, version 2
109
110         Web page: <https://openapis.org>
111
112         $ref: <http://swagger.io/v2/schema.json#>
113
114       • OpenAPI specification, version 3
115
116         Web page: <https://openapis.org>
117
118         $ref: https://spec.openapis.org/oas/3.0/schema/2019-04-02
119         <https://github.com/OAI/OpenAPI-
120         Specification/blob/master/schemas/v3.0/schema.json>
121
122         This specification is still EXPERIMENTAL.
123
124       • Swagger Petstore
125
126         This is used for unit tests, and should not be relied on by external
127         users.
128
129   Optional modules
130       • Sereal::Encoder
131
132         Installing Sereal::Encoder v4.00 (or later) will make "data_checksum"
133         in JSON::Validator::Util significantly faster. This function is used
134         both when parsing schemas and validating data.
135
136       • Format validators
137
138         See the documentation in JSON::Validator::Formats for other optional
139         modules to do validation of specific "format", such as "hostname",
140         "ipv4" and others.
141

ERROR OBJECT

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

ATTRIBUTES

147   cache_paths
148       Proxy attribute for "cache_paths" in JSON::Validator::Store.
149
150   formats
151         my $hash_ref = $jv->formats;
152         my $jv = $jv->formats(\%hash);
153
154       Holds a hash-ref, where the keys are supported JSON type "formats", and
155       the values holds a code block which can validate a given format. A code
156       block should return "undef" on success and an error string on error:
157
158         sub { return defined $_[0] && $_[0] eq "42" ? undef : "Not the answer." };
159
160       See JSON::Validator::Formats for a list of supported formats.
161
162   recursive_data_protection
163         my $jv = $jv->recursive_data_protection($bool);
164         my $bool = $jv->recursive_data_protection;
165
166       Recursive data protection is active by default, however it can be
167       deactivated by assigning a false value to the
168       "recursive_data_protection" attribute.
169
170       Recursive data protection can have a noticeable impact on memory usage
171       when validating large data structures. If you are encountering issues
172       with memory and you can guarantee that you do not have any loops in
173       your data structure then deactivating the recursive data protection may
174       help.
175
176       This attribute is EXPERIMENTAL and may change in a future release.
177
178       Disclaimer: Use at your own risk, if you have any doubt then don't use
179       it
180
181   store
182         $store = $jv->store;
183
184       Holds a JSON::Validator::Store object that caches the retrieved
185       schemas.  This object can be shared amongst different schema objects to
186       prevent a schema from having to be downloaded again.
187
188   ua
189       Proxy attribute for "ua" in JSON::Validator::Store.
190

METHODS

192   bundle
193         # These two lines does the same
194         my $schema = $jv->bundle({schema => $jv->schema->data});
195         my $schema = $jv->bundle;
196
197         # Will only bundle a section of the schema
198         my $schema = $jv->bundle({schema => $jv->schema->get("/properties/person/age")});
199
200       Used to create a new schema, where there are no "$ref" pointing to
201       external resources. This means that all the "$ref" that are found, will
202       be moved into the "definitions" key, in the returned $schema.
203
204   coerce
205         my $jv       = $jv->coerce('bool,def,num,str');
206         my $jv       = $jv->coerce('booleans,defaults,numbers,strings');
207         my $hash_ref = $jv->coerce;
208
209       Set the given type to coerce. Before enabling coercion this module is
210       very strict when it comes to validating types. Example: The string "1"
211       is not the same as the number 1, unless you have "numbers" coercion
212       enabled.
213
214       • booleans
215
216         Will convert what looks can be interpreted as a boolean (that is, an
217         actual numeric 1 or 0, and the strings "true" and "false") to a
218         JSON::PP::Boolean object. Note that "foo" is not considered a true
219         value and will fail the validation.
220
221       • defaults
222
223         Will copy the default value defined in the schema, into the input
224         structure, if the input value is non-existing.
225
226         Note that support for "default" is currently EXPERIMENTAL, and
227         enabling this might be changed in future versions.
228
229       • numbers
230
231         Will convert strings that looks like numbers, into true numbers. This
232         works for both the "integer" and "number" types.
233
234       • strings
235
236         Will convert a number into a string. This works for the "string"
237         type.
238
239   get
240         my $sub_schema = $jv->get("/x/y");
241         my $sub_schema = $jv->get(["x", "y"]);
242
243       Extract value from "schema" identified by the given JSON Pointer. Will
244       at the same time resolve $ref if found. Example:
245
246         $jv->schema({x => {'$ref' => '#/y'}, y => {'type' => 'string'}});
247         $jv->schema->get('/x')           == {'$ref' => '#/y'}
248         $jv->schema->get('/x')->{'$ref'} == '#/y'
249         $jv->get('/x')                   == {type => 'string'}
250
251       The argument can also be an array-ref with the different parts of the
252       pointer as each elements.
253
254   new
255         $jv = JSON::Validator->new(%attributes);
256         $jv = JSON::Validator->new(\%attributes);
257
258       Creates a new JSON::Validate object.
259
260   load_and_validate_schema
261         my $jv = $jv->load_and_validate_schema($schema, \%args);
262
263       Will load and validate $schema against the OpenAPI specification.
264       $schema can be anything "schema" in JSON::Validator accepts. The
265       expanded specification will be stored in "schema" in JSON::Validator on
266       success. See "schema" in JSON::Validator for the different version of
267       $url that can be accepted.
268
269       %args can be used to further instruct the validation process:
270
271       • schema
272
273         Defaults to "http://json-schema.org/draft-04/schema#", but can be any
274         structured that can be used to validate $schema.
275
276   schema
277         my $jv     = $jv->schema($json_or_yaml_string);
278         my $jv     = $jv->schema($url);
279         my $jv     = $jv->schema(\%schema);
280         my $jv     = $jv->schema(JSON::Validator::Joi->new);
281         my $jv     = $jv->schema(JSON::Validator::Schema->new);
282         my $schema = $jv->schema;
283
284       Used to set a schema from either a data structure or a URL.
285
286       $schema will be a JSON::Validator::Schema object when loaded, and
287       "undef" by default.
288
289       The $url can take many forms, but needs to point to a text file in the
290       JSON or YAML format.
291
292       •   file://...
293
294           A file on disk. Note that it is required to use the "file" scheme
295           if you want to reference absolute paths on your file system.
296
297http://... or https://...
298
299           A web resource will be fetched using the Mojo::UserAgent, stored in
300           "ua".
301
302       •   data://Some::Module/spec.json
303
304           Will load a given "spec.json" file from "Some::Module" using
305           "data_section" in JSON::Validator::Util.
306
307       •   data:///spec.json
308
309           A "data" URL without a module name will use the current package and
310           search up the call/inheritance tree.
311
312       •   Any other URL
313
314           An URL (without a recognized scheme) will be treated as a path to a
315           file on disk. If the file could not be found on disk and the path
316           starts with "/", then the will be loaded from the app defined in
317           "ua". Something like this:
318
319             $jv->ua->server->app(MyMojoApp->new);
320             $jv->ua->get('/any/other/url.json');
321
322   validate
323         my @errors = $jv->validate($data);
324
325       Validates $data against "schema". @errors will contain validation error
326       objects, in a predictable order (specifically, alphanumerically sorted
327       by the error objects' "path") or be an empty list on success.
328
329       See "ERROR OBJECT" for details.
330

SEE ALSO

332       • JSON::Validator::Formats
333
334         JSON::Validator::Formats contains utility functions for validating
335         data types. Could be useful for validating data without loading a
336         schema.
337
338       • JSON::Validator::Schema
339
340         JSON::Validator::Schema is the base class for
341         JSON::Validator::Schema::Draft4, JSON::Validator::Schema::Draft6
342         JSON::Validator::Schema::Draft7,
343         JSON::Validator::Schema::Draft201909,
344         JSON::Validator::Schema::OpenAPIv2 or
345         JSON::Validator::Schema::OpenAPIv3.
346
347       • JSON::Validator::Util
348
349         JSON::Validator::Util contains many useful function when working with
350         schemas.
351
352       • Mojolicious::Plugin::OpenAPI
353
354         Mojolicious::Plugin::OpenAPI is a plugin for Mojolicious that utilize
355         JSON::Validator and the OpenAPI specification
356         <https://www.openapis.org/> to build routes with input and output
357         validation.
358
360       Copyright (C) 2014-2021, Jan Henning Thorsen
361
362       This program is free software, you can redistribute it and/or modify it
363       under the terms of the Artistic License version 2.0.
364

AUTHOR

366       Jan Henning Thorsen - "jhthorsen@cpan.org"
367
368       Daniel Böhmer - "post@daniel-boehmer.de"
369
370       Ed J - "mohawk2@users.noreply.github.com"
371
372       Karen Etheridge - "ether@cpan.org"
373
374       Kevin Goess - "cpan@goess.org"
375
376       Martin Renvoize - "martin.renvoize@gmail.com"
377
378
379
380perl v5.34.0                      2021-07-22                JSON::Validator(3)
Impressum