++ed by:
1 non-PAUSE user
Author image Oleg G
and 1 contributors


Data::JSONSchema::Ajv - JSON Schema Validator wrapping Ajv


version 0.09


JSON Schema Validator wrapping Ajv


    use Test::More;
    use Data::JSONSchema::Ajv;

    my $ajv_options = {};
    my $my_options  = {
        draft => '04', # Defaults to '07'

    my $ajv     = Data::JSONSchema::Ajv->new($ajv_options, $my_options);

    my $validator = $ajv->make_validator(
        {    # http://json-schema.org/examples.html
            title      => "Example Schema",
            type       => "object",
            properties => {
                firstName => { type => "string" },
                lastName  => { type => "string" },
                age       => {
                    description => "Age in years",
                    type        => "integer",
                    minimum     => 0
            required => [ "firstName", "lastName" ],

    my $payload = { firstName => 'Valentina', familyName => 'Tereshkova' };

    my $result = $validator->validate($payload);

    if ($result) {
            [   {   dataPath   => "",
                    keyword    => "required",
                    message    => "should have required property 'lastName'",
                    params     => { missingProperty => "lastName" },
                    schemaPath => "#/required"
            "Expected errors thrown"
    } else {
            "validate() returned a false value, which means the example " .
            "unexpectedly validated"


This module is an offensively light-weight wrapper Ajv.

Light-weight in this context just means it's not very many lines of actual Perl



  my $ajv = Data::JSONSchema::Ajv->new(
      { v5 => $JSON::PP::true }, # Ajv options. Try: {},
      {}, # Module options. See below

Instantiates a new JavaScript::Duktape::XS environment and loads Ajv into it. Accepts two hashrefs (or undefs). The first is passed straight through to Ajv, whose options are documented here.

The second one allows you to specify options of this module:


String that contains source code of standalone version of Ajv library, which can be found here. This module already has some version (possibly not last) of Ajv hardcoded inside it and will use it if this option doesn't specified.


A JSON Schema draft version as a string. Allowable values are 04, 06, and 07. No support for multiple schemas at this time. Default is 07.


  my $validator = $ajv->make_validator( $hashref_schema OR $json_string );

Compiles your schema using Ajv and return a Data::JSONSchema::Ajv::Validator object, documented immediately below.


    $ajv->compile( $hashref_schema OR $json_string );

Same as make_validator, but doesn't return validator object. You can get validator later using get_validator (see below).



You can get validator from schema previously compiled with compile or make_validator. You can even get validator from the part of compiled schema:

    # You can compile many schemas in one ajv instance
        '$id' => "Schema_one", 
        token => {
        type => "string",
        minLength => 5
        login => {
            params => [
                {type => "boolean"},
                {type => "string"}
            returns => { type => "number" }

        '$id' => "Schema_two", 
        type => "string",
        minLength => 5

    # and then get validators using schema id and path to needed subschema
    $validator_one = $ajv->get_validator('Schema_one#/login/returns');
    $validator_two = $ajv->get_validator('Schema_two');


Need to do something else, and something magic? This is a read-only accessor to the Duktape env.


Single method object:


  my $errors = $validator->validate( $data_structure );
  my $errors = $validator->validate( \$data_structure );

Validate a data-structure against the schema. Whith some options specified (like removeAdditional, coerceTypes) Ajv may modify input data. If you want to receive this modifications you need to pass your data structure by reference: for example if you normally pass hashref or arrayref in this case you need to pass reference to hashref or reference to arrayref. If you are validating just a simple scalar like string or number you can also pass it by reference, but you'll not get any data modifications because on Ajv's side they are passed by value and can't be modified. You can try to wrap such scalars in array with one element and modify schema a little to pass this limitation. Returns undef on success, and a data-structure complaining on failure. The data-structure is whatever Ajv produces - you can either read its documentation, or be lazy and simply Data::Dumper it.


Perl has no special Boolean types. JSON (and indeed JavaScript) does. If you're really brave, you can pass in a json option to replace the underlying Cpanel::JSON::XS at instantiation.


This module was written because I couldn't get any of the other JSON Schema validators to work.

Toby Inkster wrote JSON::Schema, which I had high hopes for, because he's a smart cookie, but it seems like it's very out of date compared to modern schemas.

I was unable to get JSON::Validator to fail validation for any schema I gave it. That's probably due to having miswritten my schemas, but it didn't give me any hints, and I did get some errors along the lines of Can't locate method validate_HASH(blahblah) and so I gave up. I also find it mildly offensive that (the most excellent) Mojolicious is a dependency for a JSON tool. Additionally it doesn't validate the schemas themselves, and I'm too stupid to use a tool like that.

Test::JSON::Schema::Acceptance provides some schema tests. This passes all of thems except the ones that require going and downloading external schemas.


All the hard work was done by the guy who wrote Ajv, Evgeny Poberezkin.

This Perl wrapper written by Peter Sergeant.