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       ·   <http://spacetelescope.github.io/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

ERROR OBJECT

124       The methods "validate" and the function "validate_json" returns a list
125       of JSON::Validator::Error objects when the input data violates the
126       "schema".
127

FUNCTIONS

129   joi
130         use JSON::Validator "joi";
131         my $joi    = joi;
132         my @errors = joi($data, $joi); # same as $joi->validate($data);
133
134       Used to construct a new JSON::Validator::Joi object or perform
135       validation.
136
137   validate_json
138         use JSON::Validator "validate_json";
139         my @errors = validate_json $data, $schema;
140
141       This can be useful in web applications:
142
143         my @errors = validate_json $c->req->json, "data://main/spec.json";
144
145       See also "validate" and "ERROR OBJECT" for more details.
146

ATTRIBUTES

148   cache_paths
149         my $jv = $jv->cache_paths(\@paths);
150         my $array_ref = $jv->cache_paths;
151
152       A list of directories to where cached specifications are stored.
153       Defaults to "JSON_VALIDATOR_CACHE_PATH" environment variable and the
154       specs that is bundled with this distribution.
155
156       "JSON_VALIDATOR_CACHE_PATH" can be a list of directories, each
157       separated by ":".
158
159       See "Bundled specifications" for more details.
160
161   formats
162         my $hash_ref  = $jv->formats;
163         my $jv = $jv->formats(\%hash);
164
165       Holds a hash-ref, where the keys are supported JSON type "formats", and
166       the values holds a code block which can validate a given format. A code
167       block should return "undef" on success and an error string on error:
168
169         sub { return defined $_[0] && $_[0] eq "42" ? undef : "Not the answer." };
170
171       See JSON::Validator::Formats for a list of supported formats.
172
173   generate_definitions_path
174         my $cb = $self->generate_definitions_path;
175         my $jv = $self->generate_definitions_path(sub { my $ref = shift; return ["definitions"] });
176
177       Holds a callback that is used by "bundle" to figure out where to place
178       references. The default location is under "definitions", but this can
179       be changed to whatever you want. The input $ref variable passed on is a
180       JSON::Validator::Ref object.
181
182       This attribute is EXPERIMENTAL and might change without warning.
183
184   ua
185         my $ua        = $jv->ua;
186         my $jv = $jv->ua(Mojo::UserAgent->new);
187
188       Holds a Mojo::UserAgent object, used by "schema" to load a JSON schema
189       from remote location.
190
191       The default Mojo::UserAgent will detect proxy settings and have
192       "max_redirects" in Mojo::UserAgent set to 3.
193
194   version
195         my $int       = $jv->version;
196         my $jv = $jv->version(7);
197
198       Used to set the JSON Schema version to use. Will be set automatically
199       when using "load_and_validate_schema", unless already set.
200

METHODS

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

AUTHOR

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