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 $validator = 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         $validator->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 = $validator->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         $validator->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: <http://swagger.io/v3/schema.yaml#>
113
114         This specification is still EXPERIMENTAL.
115
116       · Swagger Petstore
117
118         This is used for unit tests, and should not be relied on by external
119         users.
120

ERROR OBJECT

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

FUNCTIONS

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

ATTRIBUTES

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

METHODS

189   bundle
190         my $schema = $validator->bundle(\%args);
191
192       Used to create a new schema, where the $ref are resolved. %args can
193       have:
194
195       · "{replace =" 1}>
196
197         Used if you want to replace the $ref inline in the schema. This
198         currently does not work if you have circular references. The default
199         is to move all the $ref definitions into the main schema with custom
200         names. Here is an example on how a $ref looks before and after:
201
202           {"$ref":"../some/place.json#/foo/bar"}
203              => {"$ref":"#/definitions/____some_place_json-_foo_bar"}
204
205           {"$ref":"http://example.com#/foo/bar"}
206              => {"$ref":"#/definitions/_http___example_com-_foo_bar"}
207
208       · "{schema =" {...}}>
209
210         Default is to use the value from the "schema" attribute.
211
212   coerce
213         my $validator = $validator->coerce(booleans => 1, numbers => 1, strings => 1);
214         my $validator = $validator->coerce({booleans => 1, numbers => 1, strings => 1});
215         my $hash_ref  = $validator->coerce;
216
217       Set the given type to coerce. Before enabling coercion this module is
218       very strict when it comes to validating types. Example: The string "1"
219       is not the same as the number 1, unless you have coercion enabled.
220
221       Loading a YAML document will enable "booleans" automatically. This
222       feature is experimental, but was added since YAML has no real concept
223       of booleans, such as Mojo::JSON or other JSON parsers.
224
225   get
226         my $sub_schema = $validator->get("/x/y");
227         my $sub_schema = $validator->get(["x", "y"]);
228
229       Extract value from "schema" identified by the given JSON Pointer. Will
230       at the same time resolve $ref if found. Example:
231
232         $validator->schema({x => {'$ref' => '#/y'}, y => {'type' => 'string'}});
233         $validator->schema->get('/x')           == undef
234         $validator->schema->get('/x')->{'$ref'} == '#/y'
235         $validator->get('/x')                   == {type => 'string'}
236
237       The argument can also be an array-ref with the different parts of the
238       pointer as each elements.
239
240   load_and_validate_schema
241         my $validator = $validator->load_and_validate_schema($schema, \%args);
242
243       Will load and validate $schema against the OpenAPI specification.
244       $schema can be anything "schema" in JSON::Validator accepts. The
245       expanded specification will be stored in "schema" in JSON::Validator on
246       success. See "schema" in JSON::Validator for the different version of
247       $url that can be accepted.
248
249       %args can be used to further instruct the validation process:
250
251       · schema
252
253         Defaults to "http://json-schema.org/draft-04/schema#", but can be any
254         structured that can be used to validate $schema.
255
256   schema
257         my $validator = $validator->schema($json_or_yaml_string);
258         my $validator = $validator->schema($url);
259         my $validator = $validator->schema(\%schema);
260         my $validator = $validator->schema(JSON::Validator::Joi->new);
261         my $schema    = $validator->schema;
262
263       Used to set a schema from either a data structure or a URL.
264
265       $schema will be a Mojo::JSON::Pointer object when loaded, and "undef"
266       by default.
267
268       The $url can take many forms, but needs to point to a text file in the
269       JSON or YAML format.
270
271       ·   file://...
272
273           A file on disk. Note that it is required to use the "file" scheme
274           if you want to reference absolute paths on your file system.
275
276       ·   http://... or https://...
277
278           A web resource will be fetched using the Mojo::UserAgent, stored in
279           "ua".
280
281       ·   data://Some::Module/spec.json
282
283           Will load a given "spec.json" file from "Some::Module" using
284           "data_section" in Mojo::Loader.
285
286       ·   data:///spec.json
287
288           A "data" URL without a module name will use the current package and
289           search up the call/inheritance tree.
290
291       ·   Any other URL
292
293           An URL (without a recognized scheme) will be treated as a path to a
294           file on disk.
295
296   singleton
297         my $validator = JSON::Validator->singleton;
298
299       Returns the JSON::Validator object used by "validate_json".
300
301   validate
302         my @errors = $validator->validate($data);
303         my @errors = $validator->validate($data, $schema);
304
305       Validates $data against a given JSON "schema". @errors will contain
306       validation error objects or be an empty list on success.
307
308       See "ERROR OBJECT" for details.
309
310       $schema is optional, but when specified, it will override schema stored
311       in "schema". Example:
312
313         $validator->validate({hero => "superwoman"}, {type => "object"});
314
315   SEE ALSO
316       · Mojolicious::Plugin::OpenAPI
317
318         Mojolicious::Plugin::OpenAPI is a plugin for Mojolicious that utilize
319         JSON::Validator and the OpenAPI specification
320         <https://www.openapis.org/> to build routes with input and output
321         validation.
322
324       Copyright (C) 2014-2018, Jan Henning Thorsen
325
326       This program is free software, you can redistribute it and/or modify it
327       under the terms of the Artistic License version 2.0.
328

AUTHOR

330       Jan Henning Thorsen - "jhthorsen@cpan.org"
331
332       Daniel Böhmer - "post@daniel-boehmer.de"
333
334       Ed J - "mohawk2@users.noreply.github.com"
335
336       Kevin Goess - "cpan@goess.org"
337
338       Martin Renvoize - "martin.renvoize@gmail.com"
339
340
341
342perl v5.28.1                      2019-02-14                JSON::Validator(3)
Impressum