forked from jhthorsen/json-validator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathREADME
284 lines (197 loc) · 8.75 KB
/
README
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
NAME
JSON::Validator - Validate data against a JSON schema
VERSION
0.85
SYNOPSIS
use JSON::Validator;
my $validator = JSON::Validator->new;
# Define a schema - http://json-schema.org/examples.html
# You can also load schema from disk or web
$validator->schema(
{
type => "object",
required => ["firstName", "lastName"],
properties => {
firstName => {type => "string"},
lastName => {type => "string"},
age => {type => "integer", minimum => 0, description => "Age in years"}
}
}
);
# Validate your data
@errors = $validator->validate({firstName => "Jan Henning", lastName => "Thorsen", age => -42});
# Do something if any errors was found
die "@errors" if @errors;
DESCRIPTION
JSON::Validator is a class for validating data against JSON schemas. You
might want to use this instead of JSON::Schema if you need to validate
data against draft 4
<https://github.com/json-schema/json-schema/tree/master/draft-04> of the
specification.
This module can be used standalone, but if you want to define a
specification for your webserver's API, then have a look at
Mojolicious::Plugin::OpenAPI, which will replace
Mojolicious::Plugin::Swagger2.
Supported schema formats
JSON::Validator can load JSON schemas in multiple formats: Plain perl
data structured (as shown in "SYNOPSIS") or files on disk/web in the
JSON/YAML format. The JSON parsing is done using Mojo::JSON, while the
YAML parsing is done with an optional modules which need to be installed
manually. JSON::Validator will look for the YAML modules in this order:
YAML::XS, YAML::Syck. The order is set by which module that performs the
best, so it might change in the future.
Resources
Here are some resources that are related to JSON schemas and validation:
* <http://json-schema.org/documentation.html>
* <http://spacetelescope.github.io/understanding-json-schema/index.htm
l>
* <https://github.com/json-schema/json-schema/>
* Swagger2
ERROR OBJECT
Overview
The method "validate" and the function "validate_json" returns error
objects when the input data violates the "schema". Each of the objects
looks like this:
bless {
message => "Some description",
path => "/json/path/to/node",
}, "JSON::Validator::Error"
See also JSON::Validator::Error.
Operators
The error object overloads the following operators:
* bool
Returns a true value.
* string
Returns the "path" and "message" part as a string: "$path:
$message".
Special cases
Have a look at the test suite
<https://github.com/jhthorsen/json-validator/tree/master/t> for
documented examples of the error cases. Especially look at "jv-allof.t",
"jv-anyof.t" and "jv-oneof.t".
The special cases for "allOf", "anyOf" and "oneOf" will contain the
error messages from all the failing rules below. It can be a bit hard to
read, so if the error message is long, then you might want to run a
smaller test with "JSON_VALIDATOR_DEBUG=1".
Example error object:
bless {
message => "(String is too long: 8/5. String is too short: 8/12)",
path => "/json/path/to/node",
}, "JSON::Validator::Error"
Note that these error messages are subject for change. Any suggestions
are most welcome!
FUNCTIONS
validate_json
use JSON::Validator "validate_json";
@errors = validate_json $data, $schema;
This can be useful in web applications:
@errors = validate_json $c->req->json, "data://main/spec.json";
See also "validate" and "ERROR OBJECT" for more details.
ATTRIBUTES
cache_dir
Deprecated in favor of "cache_paths".
cache_paths
$self = $self->cache_paths(\@paths);
$array_ref = $self->cache_paths;
Search paths to where cached specifications are stored. Defaults to
"JSON_VALIDATOR_CACHE_DIR" and the bundled spec files that are shipped
with this distribution.
JSON_VALIDATOR_CACHE_DIR=/cache/dir:/some/other/location perl script.pl
To download a file and add it to the cache, do this:
$ curl http://swagger.io/v2/schema.json > /cache/dir/$(md5 -qs http://swagger.io/v2/schema.json)
Files referenced to an URL will automatically be cached if the first
path in "cache_paths" is writable.
formats
$hash_ref = $self->formats;
$self = $self->formats(\%hash);
Holds a hash-ref, where the keys are supported JSON type "formats", and
the values holds a code block which can validate a given format.
Note! The modules mentioned below are optional.
* date-time
An RFC3339 timestamp in UTC time. This is formatted as
"YYYY-MM-DDThh:mm:ss.fffZ". The milliseconds portion (".fff") is
optional
* email
Validated against the RFC5322 spec.
* hostname
Will be validated using Data::Validate::Domain if installed.
* ipv4
Will be validated using Data::Validate::IP if installed or fall back
to a plain IPv4 IP regex.
* ipv6
Will be validated using Data::Validate::IP if installed.
* regex
EXPERIMENTAL. Will check if the string is a regex, using "qr{...}".
* uri
Validated against the RFC3986 spec.
resolver
$code = $self->resolver;
$self = $self->resolver(sub { my ($self, $namespace, $refs) = @_; });
Set this to a sub without any logic if you want to skip resolving
references, like this:
$self->resolver(sub {});
This attribute is EXPERIMENTAL.
ua
$ua = $self->ua;
$self = $self->ua(Mojo::UserAgent->new);
Holds a Mojo::UserAgent object, used by "schema" to load a JSON schema
from remote location.
Note that the default Mojo::UserAgent will detect proxy settings and
have "max_redirects" in Mojo::UserAgent set to 3. (These settings are
EXPERIMENTAL and might change without a warning)
METHODS
coerce
$self = $self->coerce(booleans => 1, numbers => 1, strings => 1);
$self = $self->coerce({booleans => 1, numbers => 1, strings => 1});
$self = $self->coerce(1) # enable all
$hash = $self->coerce;
Set the given type to coerce. Before enabling coercion this module is
very strict when it comes to validating types. Example: The string "1"
is not the same as the number 1, unless you have coercion enabled.
WARNING! Enabling coercion might hide bugs in your api, which would have
been detected if you were strict. For example JavaScript is very picky
on a number being an actual number. This module tries it best to convert
the data on the fly into the proper value, but this means that you unit
tests might be ok, but the client side libraries (that care about types)
might break.
Loading a YAML document will enable "booleans" automatically. This
feature is experimental, but was added since YAML has no real concept of
booleans, such as Mojo::JSON or other JSON parsers.
The coercion rules are EXPERIMENTAL and will be tighten/loosen if bugs
are reported. See <https://github.com/jhthorsen/json-validator/issues/8>
for more details.
schema
$self = $self->schema(\%schema);
$self = $self->schema($url);
$schema = $self->schema;
Used to set a schema from either a data structure or a URL.
$schema will be a Mojo::JSON::Pointer object when loaded, and "undef" by
default.
The $url can take many forms, but needs to point to a text file in the
JSON or YAML format.
* http://... or https://...
A web resource will be fetched using the Mojo::UserAgent, stored in
"ua".
* data://Some::Module/file.name
This version will use "data_section" in Mojo::Loader to load
"file.name" from the module "Some::Module".
* /path/to/file
An URL (without a recognized scheme) will be loaded from disk.
singleton
$self = $class->singleton;
Returns the JSON::Validator object used by "validate_json".
validate
@errors = $self->validate($data);
@errors = $self->validate($data, $schema);
Validates $data against a given JSON "schema". @errors will contain
validation error objects or be an empty list on success.
See "ERROR OBJECT" for details.
$schema is optional, but when specified, it will override schema stored
in "schema". Example:
$self->validate({hero => "superwoman"}, {type => "object"});
COPYRIGHT AND LICENSE
Copyright (C) 2014-2015, Jan Henning Thorsen
This program is free software, you can redistribute it and/or modify it
under the terms of the Artistic License version 2.0.
AUTHOR
Jan Henning Thorsen - "jhthorsen@cpan.org"