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

DESCRIPTION

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

ERROR OBJECT

137       The methods "validate" and the function "validate_json" returns a list
138       of JSON::Validator::Error objects when the input data violates the
139       "schema".
140

FUNCTIONS

142   joi
143       DEPRECATED.
144
145   validate_json
146       DEPRECATED.
147

ATTRIBUTES

149   cache_paths
150         my $jv        = $jv->cache_paths(\@paths);
151         my $array_ref = $jv->cache_paths;
152
153       A list of directories to where cached specifications are stored.
154       Defaults to "JSON_VALIDATOR_CACHE_PATH" environment variable and the
155       specs that is bundled with this distribution.
156
157       "JSON_VALIDATOR_CACHE_PATH" can be a list of directories, each
158       separated by ":".
159
160       See "Bundled specifications" for more details.
161
162   formats
163         my $hash_ref  = $jv->formats;
164         my $jv = $jv->formats(\%hash);
165
166       Holds a hash-ref, where the keys are supported JSON type "formats", and
167       the values holds a code block which can validate a given format. A code
168       block should return "undef" on success and an error string on error:
169
170         sub { return defined $_[0] && $_[0] eq "42" ? undef : "Not the answer." };
171
172       See JSON::Validator::Formats for a list of supported formats.
173
174   ua
175         my $ua = $jv->ua;
176         my $jv = $jv->ua(Mojo::UserAgent->new);
177
178       Holds a Mojo::UserAgent object, used by "schema" to load a JSON schema
179       from remote location.
180
181       The default Mojo::UserAgent will detect proxy settings and have
182       "max_redirects" in Mojo::UserAgent set to 3.
183
184   version
185       DEPRECATED.
186

METHODS

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

AUTHOR

349       Jan Henning Thorsen - "jhthorsen@cpan.org"
350
351       Daniel Böhmer - "post@daniel-boehmer.de"
352
353       Ed J - "mohawk2@users.noreply.github.com"
354
355       Karen Etheridge - "ether@cpan.org"
356
357       Kevin Goess - "cpan@goess.org"
358
359       Martin Renvoize - "martin.renvoize@gmail.com"
360
361
362
363perl v5.32.0                      2020-07-28                JSON::Validator(3)
Impressum