JSON::Validator(3)

πŸ’– JSON::Validator πŸ’–

okay bestie, buckle up β€” this is the JSON::Validator(3) page from the User Contributed Perl Documentation, and it's genuinely iconic. it's the module that checks your data against a JSON schema, and honestly? it ate. let's get into it 🫢


✨ NAME ✨

JSON::Validator β€” validate data against a JSON schema. that's it, that's the whole vibe. no cap. πŸ’…


✨ SYNOPSIS ✨

🌸 Using a schema object

so JSON::Validator::Schema or any of the sub classes can be used instead of JSON::Validator, bestie. the ONLY reason you'd use JSON::Validator directly is if you don't know the schema version up front. that's literally it. lowkey niche but valid. ✨

πŸŽ€ Basics

use JSON::Validator;
my $jv = JSON::Validator->new;

# Define a schema - http://json-schema.org/learn/miscellaneous-examples.html
# You can also load schema from disk or web
$jv->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
my @errors = $jv->validate({firstName => "Jan Henning", lastName => "Thorsen", age => -42});

# Do something if any errors was found
die "@errors" if @errors;

the way this just works 😭 define a schema, validate your data, die if there's errors. main character energy fr fr.

πŸ¦‹ Using joi

# Use joi() to build the schema
use JSON::Validator::Joi 'joi';

$jv->schema(joi->object->props({
  firstName => joi->string->required,
  lastName  => joi->string->required,
  age       => joi->integer->min(0),
}));

# joi() can also validate directly
my @errors = joi(
  {firstName => "Jan Henning", lastName => "Thorsen", age => -42},
  joi->object->props({
    firstName => joi->string->required,
    lastName  => joi->string->required,
    age       => joi->integer->min(0),
  }),
);

joi is the elegant DSL schema-builder and it's giving✨ β€” build the schema with joi(), or validate directly with joi(). obsessed. πŸ’–


✨ DESCRIPTION ✨

JSON::Validator is a data structure validation library based around JSON Schema <https://json-schema.org/>. this module can be used directly with a JSON schema, or you can use the elegant DSL schema-builder JSON::Validator::Joi to define the schema programmatically. pick your fighter, both slay. πŸ‘‘

🌈 Supported schema formats

JSON::Validator can load JSON schemas in multiple formats: plain perl data structured (as shown in "SYNOPSIS"), JSON or YAML. the JSON parsing is done with Mojo::JSON, while YAML files requires YAML::PP or YAML::XS. ikyk. 🧚

πŸ“ Resources

here are some resources that are related to JSON schemas and validation β€” go be nosy, bestie:

πŸ’œ Bundled specifications

this module comes with some JSON specifications bundled, so your application don't have to fetch those from the web. these specifications should be up to date, but please submit an issue if they are not β€” like, genuinely, they want to know. πŸ™ˆ

files referenced to an URL will automatically be cached if the first element in "cache_paths" is a writable directory. ⚠️ note that the cache headers for the remote assets are not honored, so you will manually need to remove any cached file, should you need to refresh them. no auto-refresh for you, bestie. πŸ’€

to download and cache an online asset, do this:

JSON_VALIDATOR_CACHE_PATH=/some/writable/directory perl myapp.pl

here is the list of the bundled specifications:

  • JSON schema, draft 4, 6, 7, 2019-09.

Web page: <http://json-schema.org>

$ref: <http://json-schema.org/draft-04/schema#>, <http://json-schema.org/draft-06/schema#>, <http://json-schema.org/draft-07/schema#>.

  • JSON schema for JSONPatch files

Web page: <http://jsonpatch.com>

$ref: <http://json.schemastore.org/json-patch#>

  • Swagger / OpenAPI specification, version 2

Web page: <https://openapis.org>

$ref: <http://swagger.io/v2/schema.json#>

  • OpenAPI specification, version 3

Web page: <https://openapis.org>

$ref: https://spec.openapis.org/oas/3.0/schema/2019-04-02 <https://github.com/OAI/OpenAPI-Specification/blob/master/schemas/v3.0/schema.json>

this specification is still EXPERIMENTAL. you've been warned, bestie. 😭
  • Swagger Petstore

this is used for unit tests, and should not be relied on by external users. it's giving "internal use only" energy. πŸ™…

🌸 Optional modules

  • Sereal::Encoder

installing Sereal::Encoder v4.00 (or later) will make data_checksum in JSON::Validator::Util significantly faster. this function is used both when parsing schemas and validating data. speed demon vibes. πŸ”₯

  • Format validators

see the documentation in JSON::Validator::Formats for other optional modules to do validation of specific format, such as hostname, ipv4 and others. go read it, it's tea. β˜•


✨ ATTRIBUTES ✨

πŸŽ€ cache_paths

proxy attribute for "cache_paths" in JSON::Validator::Store. simple as that. πŸ’…

πŸ¦‹ formats

this attribute will be used as default value for "formats" in JSON::Validator::Schema. it is highly recommended to change this directly on the "schema" instead:

$jv->formats(...);         # Legacy
$jv->schema->formats(...); # Recommended way

like, do the recommended one, bestie. the legacy one is lowkey a vibe but not the move. ✨

πŸ“ recursive_data_protection

this attribute will be used as default value for "recursive_data_protection" in JSON::Validator::Schema. again, highly recommended to change this directly on the "schema" instead:

$jv->recursive_data_protection(...);         # Legacy
$jv->schema->recursive_data_protection(...); # Recommended way

same energy as above, fr fr. 🌸

πŸ’œ store

$store = $jv->store;

holds a JSON::Validator::Store object that caches the retrieved schemas. this object will be shared amongst different "schema" objects to prevent a schema from having to be downloaded again. sharing is caring, periodt. 🫢

πŸ‘‘ ua

proxy attribute for "ua" in JSON::Validator::Store. that's the whole bullet. short and iconic. ⭐


✨ METHODS ✨

🧚 bundle

this method can be used to get a bundled version of "schema". it will however return a data-structure instead of a new object. see "bundle" in JSON::Validator::Schema for an alternative. πŸ‘€

# These two lines does the same
$data = $jv->bundle;
$data = $jv->schema->bundle->data;

# Recommended way
$schema = $jv->schema->bundle;

πŸ’– coerce

this attribute will be used as default value for "coerce" in JSON::Validator::Schema. it is highly recommended to change this directly on the "schema" instead:

$jv->coerce(...);         # Legacy
$jv->schema->coerce(...); # Recommended way

(do you see a pattern? yes. the pattern is real. πŸ’…)

🌈 get

proxy method for "get" in JSON::Validator::Schema. that's the whole thing. slay. ✨

πŸŽ€ new

$jv = JSON::Validator->new(%attributes);
$jv = JSON::Validator->new(\%attributes);

creates a new JSON::Validate object. (yes, that's literally what the original says β€” JSON::Validate β€” not me, bestie. 😭) either pass a list or a hash ref, both work. 🫢

πŸ¦‹ load_and_validate_schema

⚠️ this method will be deprecated in the future. see "errors" in JSON::Validator::Schema and "is_invalid" in JSON::Validator::Schema instead. don't get attached. πŸ’€

πŸ“ schema

$jv     = $jv->schema($json_or_yaml_string);
$jv     = $jv->schema($url);
$jv     = $jv->schema(\%schema);
$jv     = $jv->schema(JSON::Validator::Joi->new);
$jv     = $jv->schema(JSON::Validator::Schema->new);
$schema = $jv->schema;

used to set a schema from either a data structure or a URL. πŸ“₯

$schema will be an instance of JSON::Validator::Schema::Draft4, JSON::Validator::Schema::Draft6, JSON::Validator::Schema::Draft7, JSON::Validator::Schema::Draft201909, JSON::Validator::Schema::OpenAPIv2, JSON::Validator::Schema::OpenAPIv3 or JSON::Validator::Schema. it's giving "pick your era". 🌈

the $url can take many forms, but needs to point to a text file in the JSON or YAML format. here's the menu:

  • file://...

a file on disk. ⚠️ note that it is required to use the "file" scheme if you want to reference absolute paths on your file system. like, do not skip the scheme. πŸ™…

  • http://... or https://...

a web resource will be fetched using the Mojo::UserAgent, stored in "ua". internet girlie behavior. 🌐

  • data://Some::Module/spec.json

will load a given spec.json file from Some::Module using data_section in JSON::Validator::Util. so convenient. ✨

  • data:///spec.json

a "data" URL without a module name will use the current package and search up the call/inheritance tree. yes, it climbs the family tree. πŸ‘‘

  • Any other URL

a URL (without a recognized scheme) will be treated as a path to a file on disk. if the file could not be found on disk and the path starts with /, then the will be loaded from the app defined in "ua". something like this:

$jv->ua->server->app(MyMojoApp->new);
$jv->ua->get('/any/other/url.json');

yes, the original says "then the will be loaded" β€” leaving that exactly as-is, bestie, no edits. πŸ˜­πŸ’…

πŸ’œ validate

proxy method for "validate" in JSON::Validator::Schema. the whole point of the module, honestly. 🌟


✨ SEE ALSO ✨

  • JSON::Validator::Formats

JSON::Validator::Formats contains utility functions for validating data types. could be useful for validating data without loading a schema. no schema needed, that's the tea. β˜•

  • JSON::Validator::Schema

JSON::Validator::Schema is the base class for JSON::Validator::Schema::Draft4, JSON::Validator::Schema::Draft6, JSON::Validator::Schema::Draft7, JSON::Validator::Schema::Draft201909, JSON::Validator::Schema::OpenAPIv2 or JSON::Validator::Schema::OpenAPIv3. the mother of them all. πŸ‘‘

  • JSON::Validator::Util

JSON::Validator::Util contains many useful function when working with schemas. (yes, "function" β€” original wording, keeping it 🫢)

  • Mojolicious::Plugin::OpenAPI

Mojolicious::Plugin::OpenAPI is a plugin for Mojolicious that utilize JSON::Validator and the OpenAPI specification <https://www.openapis.org/> to build routes with input and output validation. genuinely iconic combo. πŸ”₯


Copyright (C) 2014-2021, 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. πŸŽ€


✨ AUTHORS ✨

🌸 Project Founder

Jan Henning Thorsen - "jhthorsen@cpan.org" β€” the founder, the legend, the main character. πŸ‘‘

πŸ¦‹ Contributors

shoutout to everyone who helped, fr fr, y'all ate:

  • Aleksandr Orlenko
  • Alexander Hartmaier
  • Alexander Karelas
  • Bernhard Graf
  • Brad Barden
  • Dagfinn Ilmari MannsΓ₯ker
  • Daniel BΓΆhmer
  • David Cantrell
  • Ed J
  • Ere Maijala
  • Fabrizio Gennari
  • Ilya Rassadin
  • Jason Cooper
  • Karen Etheridge
  • Kenichi Ishigaki
  • Kevin M. Goess
  • Kirill Matusov
  • Krasimir Berov
  • Lari Taskula
  • Lee Johnson
  • Martin Renvoize
  • Mattias PΓ€ivΓ€rinta
  • Michael Jemmeson
  • Michael Schout
  • Mohammad S Anwar
  • Nick Morrott
  • Pierre-Aymeric Masse
  • Roy Storey
  • Russell Jenkins
  • Sebastian Riedel
  • Stephan Hradek
  • Tim Stallard
  • Zoffix Znet

and that's the page, bestie! πŸŽ€ this one's from perl v5.42.0, dated 2025-03-17, and it's all wrapped up β€” go validate something and slay. πŸ’…βœ¨πŸ¦‹

πŸ“¦ where this page comes from