Ruby JSON Schema Validator

This library is intended to provide Ruby with an interface for validating JSON objects against a JSON schema conforming to JSON Schema Draft 3.

Dependencies

The JSON::Schema library depends on the ruby JSON gem (json). Support for YAJL and other Ruby parsers is planned.

Installation

From rubygems.org:


gem install json-schema

From the git repo:


$ gem build json-schema.gemspec
$ gem install json-schema-0.1.14.gem

Basic Usage

Two base validation methods exist: validate and validate!. The first returns a boolean on whether a validation attempt passes and the latter will throw a JSON::Schema::ValidationError with an appropriate message/trace on where the validation failed.

Both methods take two arguments, which can be either a JSON string, a file containing JSON, or a Ruby object representing JSON data. The first argument to these methods is always the schema, the second is always the data to validate.

By default, the validator uses (and only supports) the JSON Schema Draft 3 specification for validation; however, the user is free to specify additional specifications or extend existing ones.

Validate Ruby objects against a Ruby schema


require 'rubygems'
require 'json-schema'

schema = {
  "type" => "object",
  "properties" => {
    "a" => {"type" => "integer", "required" => true}
  }
}

data = {
  "a" => 5
}

JSON::Validator.validate(schema, data)

Validate a JSON string against a JSON schema file


require 'rubygems'
require 'json-schema'
  
JSON::Validator.validate('schema.json', "{'a' : 5}")

Validate a list of objects against a schema that represents the individual objects


require 'rubygems'
require 'json-schema'

data = ['user','user','user']
JSON::Validator.validate('user.json', data, :list => true)

Catch a validation error and print it out


require 'rubygems'
require 'json-schema'
  
schema = {
  "type" => "object",
  "properties" => {
    "a" => {"type" => "integer", "required" => true}
  }
}
  
data = {
  "a" => "taco"
}

begin
  JSON::Validator.validate!(schema, data)
rescue JSON::Schema::ValidationError
  puts $!.message
end

Extend an existing schema and validating against it

For this example, we are going to extend the JSON Schema Draft 3 specification by adding a ‘bitwise-and’ property for validation.


require 'rubygems'
require 'json-schema'
  
class BitwiseAndAttribute < JSON::Schema::Attribute
  def self.validate(current_schema, data, fragments, validator, options = {})
    if data.is_a?(Integer) && data & current_schema.schema['bitwise-and'].to_i == 0
      message = "The property '#{build_fragment(fragments)}' did not evaluate  to true when bitwise-AND'd with  #{current_schema.schema['bitwise-or']}"
      raise JSON::Schema::ValidationError.new(message, fragments, current_schema)
    end
  end
end

class ExtendedSchema < JSON::Schema::Validator
  def initialize
    super
    extend_schema_definition("http://json-schema.org/draft-03/schema#")
    @attributes["bitwise-and"] = BitwiseAndAttribute
    @uri = URI.parse("http://test.com/test.json")
  end
  
  JSON::Validator.register_validator(self.new)
end

schema = {
  "$schema" => "http://test.com/test.json",
  "properties" => {
    "a" => {
      "bitwise-and" => 1
    },
    "b" => {
      "type" => "string"
    }
  }
}

data = {
  "a" => 0
}

data = {"a" => 1, "b" => "taco"}
JSON::Validator.validate(schema,data) # => true
data = {"a" => 1, "b" => 5}
JSON::Validator.validate(schema,data) # => false
data = {"a" => 0, "b" => "taco"}
JSON::Validator.validate(schema,data) # => false

Notes

The following core schema attributes are not implemented:

  • default – This library aims to solely be a validator and does not modify an object it is validating.

The ‘format’ attribute is only validated for the following values:

  • date-time
  • date
  • time
  • ip-address
  • ipv6

All other ‘format’ attribute values are simply checked to ensure the instance value is of the correct datatype (e.g., an instance value is validated to be an integer or a float in the case of ‘utc-millisec’).

Additionally, JSON::Validator does not handle any json hyperschema attributes.