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