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 requires YAML::PP or
59 YAML::XS.
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
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
142 joi
143 DEPRECATED.
144
145 validate_json
146 DEPRECATED.
147
149 cache_paths
150 Proxy attribtue for "cache_paths" in JSON::Validator::Store.
151
152 formats
153 my $hash_ref = $jv->formats;
154 my $jv = $jv->formats(\%hash);
155
156 Holds a hash-ref, where the keys are supported JSON type "formats", and
157 the values holds a code block which can validate a given format. A code
158 block should return "undef" on success and an error string on error:
159
160 sub { return defined $_[0] && $_[0] eq "42" ? undef : "Not the answer." };
161
162 See JSON::Validator::Formats for a list of supported formats.
163
164 recursive_data_protection
165 my $jv = $jv->recursive_data_protections( $boolean );
166 my $boolean = $jv->recursive_data_protection;
167
168 Recursive data protection is active by default, however it can be
169 deactivated by assigning a false value to the
170 "recursive_data_protection" attribute.
171
172 Recursive data protection can have a noticeable impact on memory usage
173 when validating large data structures. If you are encountering issues
174 with memory and you can guarantee that you do not have any loops in
175 your data structure then deactivating the recursive data protection may
176 help.
177
178 This attribute is EXPERIMENTAL and may change in a future release.
179
180 Disclaimer: Use at your own risk, if you have any doubt then don't use
181 it
182
183 ua
184 Proxy attribtue for "ua" in JSON::Validator::Store.
185
186 version
187 DEPRECATED.
188
190 bundle
191 # These two lines does the same
192 my $schema = $jv->bundle({schema => $jv->schema->data});
193 my $schema = $jv->bundle;
194
195 # Will only bundle a section of the schema
196 my $schema = $jv->bundle({schema => $jv->schema->get("/properties/person/age")});
197
198 Used to create a new schema, where there are no "$ref" pointing to
199 external resources. This means that all the "$ref" that are found, will
200 be moved into the "definitions" key, in the returned $schema.
201
202 coerce
203 my $jv = $jv->coerce('bool,def,num,str');
204 my $jv = $jv->coerce('booleans,defaults,numbers,strings');
205 my $hash_ref = $jv->coerce;
206
207 Set the given type to coerce. Before enabling coercion this module is
208 very strict when it comes to validating types. Example: The string "1"
209 is not the same as the number 1, unless you have "numbers" coercion
210 enabled.
211
212 • booleans
213
214 Will convert what looks can be interpreted as a boolean (that is, an
215 actual numeric 1 or 0, and the strings "true" and "false") 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 get
238 my $sub_schema = $jv->get("/x/y");
239 my $sub_schema = $jv->get(["x", "y"]);
240
241 Extract value from "schema" identified by the given JSON Pointer. Will
242 at the same time resolve $ref if found. Example:
243
244 $jv->schema({x => {'$ref' => '#/y'}, y => {'type' => 'string'}});
245 $jv->schema->get('/x') == {'$ref' => '#/y'}
246 $jv->schema->get('/x')->{'$ref'} == '#/y'
247 $jv->get('/x') == {type => 'string'}
248
249 The argument can also be an array-ref with the different parts of the
250 pointer as each elements.
251
252 new
253 $jv = JSON::Validator->new(%attributes);
254 $jv = JSON::Validator->new(\%attributes);
255
256 Creates a new JSON::Validate object.
257
258 load_and_validate_schema
259 my $jv = $jv->load_and_validate_schema($schema, \%args);
260
261 Will load and validate $schema against the OpenAPI specification.
262 $schema can be anything "schema" in JSON::Validator accepts. The
263 expanded specification will be stored in "schema" in JSON::Validator on
264 success. See "schema" in JSON::Validator for the different version of
265 $url that can be accepted.
266
267 %args can be used to further instruct the validation process:
268
269 • schema
270
271 Defaults to "http://json-schema.org/draft-04/schema#", but can be any
272 structured that can be used to validate $schema.
273
274 schema
275 my $jv = $jv->schema($json_or_yaml_string);
276 my $jv = $jv->schema($url);
277 my $jv = $jv->schema(\%schema);
278 my $jv = $jv->schema(JSON::Validator::Joi->new);
279 my $schema = $jv->schema;
280
281 Used to set a schema from either a data structure or a URL.
282
283 $schema will be a JSON::Validator::Schema object when loaded, and
284 "undef" by default.
285
286 The $url can take many forms, but needs to point to a text file in the
287 JSON or YAML format.
288
289 • file://...
290
291 A file on disk. Note that it is required to use the "file" scheme
292 if you want to reference absolute paths on your file system.
293
294 • http://... or https://...
295
296 A web resource will be fetched using the Mojo::UserAgent, stored in
297 "ua".
298
299 • data://Some::Module/spec.json
300
301 Will load a given "spec.json" file from "Some::Module" using
302 "data_section" in JSON::Validator::Util.
303
304 • data:///spec.json
305
306 A "data" URL without a module name will use the current package and
307 search up the call/inheritance tree.
308
309 • Any other URL
310
311 An URL (without a recognized scheme) will be treated as a path to a
312 file on disk. If the file could not be found on disk and the path
313 starts with "/", then the will be loaded from the app defined in
314 "ua". Something like this:
315
316 $jv->ua->server->app(MyMojoApp->new);
317 $jv->ua->get('/any/other/url.json');
318
319 singleton
320 DEPRECATED.
321
322 validate
323 my @errors = $jv->validate($data);
324 my @errors = $jv->validate($data, $schema);
325
326 Validates $data against a given JSON "schema". @errors will contain
327 validation error objects, in a predictable order (specifically,
328 ASCIIbetically sorted by the error objects' "path") or be an empty list
329 on success.
330
331 See "ERROR OBJECT" for details.
332
333 $schema is optional, but when specified, it will override schema stored
334 in "schema". Example:
335
336 $jv->validate({hero => "superwoman"}, {type => "object"});
337
338 SEE ALSO
339 • Mojolicious::Plugin::OpenAPI
340
341 Mojolicious::Plugin::OpenAPI is a plugin for Mojolicious that utilize
342 JSON::Validator and the OpenAPI specification
343 <https://www.openapis.org/> to build routes with input and output
344 validation.
345
347 Copyright (C) 2014-2018, Jan Henning Thorsen
348
349 This program is free software, you can redistribute it and/or modify it
350 under the terms of the Artistic License version 2.0.
351
353 Jan Henning Thorsen - "jhthorsen@cpan.org"
354
355 Daniel Böhmer - "post@daniel-boehmer.de"
356
357 Ed J - "mohawk2@users.noreply.github.com"
358
359 Karen Etheridge - "ether@cpan.org"
360
361 Kevin Goess - "cpan@goess.org"
362
363 Martin Renvoize - "martin.renvoize@gmail.com"
364
365
366
367perl v5.32.1 2021-01-31 JSON::Validator(3)