### Installing json-schema Gem from Git Repository (Shell) Source: https://github.com/voxpupuli/json-schema/blob/master/README.md These commands build the `json-schema` gem from a local Git repository and then install it. This is useful for development or installing specific versions not yet on RubyGems. ```Shell gem build json-schema.gemspec gem install json-schema-*.gem ``` -------------------------------- ### Installing json-schema Gem from RubyGems (Shell) Source: https://github.com/voxpupuli/json-schema/blob/master/README.md This command installs the `json-schema` gem from the official RubyGems repository. It is the standard way to add the library to your Ruby project. ```Shell gem install json-schema ``` -------------------------------- ### Validating the Schema Itself with Ruby Source: https://github.com/voxpupuli/json-schema/blob/master/README.md This example illustrates the `:validate_schema` option, which performs an initial validation of the provided schema against the JSON Schema specification. This ensures that the schema itself is well-formed and valid before it's used to validate the actual JSON data. ```Ruby JSON::Validator.validate(schema, { "a" => 1 }, :validate_schema => true) JSON::Validator.validate({ "required" => true }, { "a" => 1 }, :validate_schema => true) ``` -------------------------------- ### Setting JSON Backend for JSON Schema Validator in Ruby Source: https://github.com/voxpupuli/json-schema/blob/master/README.md This snippet shows how to explicitly set the JSON parsing backend for the `JSON::Validator` library. By default, `yajl-ruby` is preferred if installed, but this line forces the use of the standard `json` library, which might be necessary for specific compatibility or performance requirements. ```Ruby JSON::Validator.json_backend = :json ``` -------------------------------- ### Defining a JSON Schema in Ruby Source: https://github.com/voxpupuli/json-schema/blob/master/README.md This snippet defines a sample JSON schema as a Ruby hash. It specifies an object with required properties 'a' (integer with default) and 'b' (an object containing 'x' as an integer), used for subsequent validation examples. ```Ruby require "json-schema" schema = { "type"=>"object", "required" => ["a"], "properties" => { "a" => { "type" => "integer", "default" => 42 }, "b" => { "type" => "object", "properties" => { "x" => { "type" => "integer" } } } } } ``` -------------------------------- ### Validating with Older JSON Schema Drafts in Ruby Source: https://github.com/voxpupuli/json-schema/blob/master/README.md This example demonstrates using the `:version` option to specify an older JSON Schema draft for validation. This is crucial for compatibility when working with schemas that adhere to previous versions of the JSON Schema specification, ensuring correct interpretation of schema rules. ```Ruby v2_schema = { "type" => "object", "properties" => { "a" => { "type" => "integer" } } } JSON::Validator.validate(v2_schema, {}, :version => :draft2) JSON::Validator.validate(v2_schema, {}) ``` -------------------------------- ### Validating JSON from a URI or File Path in Ruby Source: https://github.com/voxpupuli/json-schema/blob/master/README.md This example demonstrates the `:uri` option, which instructs the validator to interpret the input data as a URI or file path. It's useful for validating JSON content loaded directly from a file or a remote resource, ensuring the input is a string representing a path rather than parsed data. ```Ruby File.write("data.json", '{ "a": 1 }') JSON::Validator.validate(schema, "data.json", :uri => true) begin JSON::Validator.validate(schema, { "a" => 1 }, :uri => true) rescue TypeError => e e.message end ``` -------------------------------- ### Enforcing Strict Validation with Ruby Source: https://github.com/voxpupuli/json-schema/blob/master/README.md This example shows the effect of the `:strict` option, which implicitly sets all properties as required and disallows additional properties. It ensures that the validated JSON strictly adheres to the schema's defined structure, rejecting any missing required fields or undeclared properties. ```Ruby JSON::Validator.validate(schema, { "a" => 1, "b" => { "x" => 2 } }, :strict => true) JSON::Validator.validate(schema, { "a" => 1, "b" => { "x" => 2 }, "c" => 3 }, :strict => true) JSON::Validator.validate(schema, { "a" => 1 }, :strict => true) ``` -------------------------------- ### Validating a List of Objects with Ruby Source: https://github.com/voxpupuli/json-schema/blob/master/README.md This example illustrates using the `:list` option to validate an array of JSON objects against a schema designed for a single object. When `:list` is true, each element in the array is validated individually against the provided schema. Without it, the entire array is treated as a single entity, leading to validation failure if the schema expects an object. ```Ruby JSON::Validator.validate(schema, [{"a" => 1}, {"a" => 2}, {"a" => 3}], :list => true) JSON::Validator.validate(schema, [{"a" => 1}, {"a" => 2}, {"a" => 3}]) ``` -------------------------------- ### Registering Custom Format Validators in Ruby Source: https://github.com/voxpupuli/json-schema/blob/master/README.md Illustrates how to define and register custom format validators for JSON Schema. It shows creating a `Proc` that raises `JSON::Schema::CustomFormatError` for invalid values, registering it for specific schema drafts, and then using `fully_validate` to demonstrate its effect on validation errors. Also includes examples of deregistering and restoring default formats. ```Ruby require "json-schema" format_proc = -> value { raise JSON::Schema::CustomFormatError.new("must be 42") unless value == "42" } # register the proc for format 'the-answer' for draft4 schema JSON::Validator.register_format_validator("the-answer", format_proc, ["draft4"]) # omitting the version parameter uses ["draft1", "draft2", "draft3", "draft4"] as default JSON::Validator.register_format_validator("the-answer", format_proc) # deregistering the custom validator # (also ["draft1", "draft2", "draft3", "draft4"] as default version) JSON::Validator.deregister_format_validator('the-answer', ["draft4"]) # shortcut to restore the default formats for validators (same default as before) JSON::Validator.restore_default_formats(["draft4"]) # with the validator registered as above, the following results in # ["The property '#a' must be 42"] as returned errors schema = { "$schema" => "http://json-schema.org/draft-04/schema#", "properties" => { "a" => { "type" => "string", "format" => "the-answer" } } } errors = JSON::Validator.fully_validate(schema, {"a" => "23"}) ``` -------------------------------- ### Controlling Integer String Parsing in Ruby Source: https://github.com/voxpupuli/json-schema/blob/master/README.md This example demonstrates the `:parse_integer` option. When `false`, it prevents the validator from automatically parsing string values that look like integers into actual integers. This is important for strict type checking where a string '23' should not be considered a valid integer type. ```Ruby JSON::Validator.validate({type: "integer"}, "23") JSON::Validator.validate({type: "integer"}, "23", parse_integer: false) JSON::Validator.validate({type: "string"}, "123", parse_integer: false) JSON::Validator.validate({type: "string"}, "123") ``` -------------------------------- ### Extending JSON Schema with Custom Bitwise-AND Attribute in Ruby Source: https://github.com/voxpupuli/json-schema/blob/master/README.md This snippet demonstrates how to extend the JSON Schema Draft 3 specification by adding a custom 'bitwise-and' attribute. It defines `BitwiseAndAttribute` for validation logic, creates `ExtendedSchema` to register this attribute, and provides examples of validating data against a schema using this new custom attribute. ```Ruby require "json-schema" class BitwiseAndAttribute < JSON::Schema::Attribute def self.validate(current_schema, data, fragments, processor, 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']}" validation_error(processor, message, fragments, current_schema, self, options[:record_errors]) end end end class ExtendedSchema < JSON::Schema::Draft3 def initialize super @attributes["bitwise-and"] = BitwiseAndAttribute @uri = JSON::Util::URI.parse("http://test.com/test.json") @names = ["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 ``` -------------------------------- ### Controlling Remote Schema Resolution in Ruby Source: https://github.com/voxpupuli/json-schema/blob/master/README.md Explains how to manage remote schema resolution to prevent HTTP calls or file reads. It shows how to pre-register schemas using `JSON::Validator.add_schema` and how to configure the default `JSON::Schema::Reader` instance to control whether URIs or local files are accepted for schema resolution. ```Ruby schema = JSON::Schema.new(some_schema_definition, Addressable::URI.parse('http://example.com/my-schema')) JSON::Validator.add_schema(schema) ``` ```Ruby # Change the default schema reader used JSON::Validator.schema_reader = JSON::Schema::Reader.new(:accept_uri => true, :accept_file => false) ``` -------------------------------- ### Basic JSON Schema Validation in Ruby Source: https://github.com/voxpupuli/json-schema/blob/master/README.md This snippet demonstrates various ways to use the `json-schema` library for validation in Ruby. It covers validating Ruby objects against a Ruby schema, validating JSON strings against a schema file, and handling validation failures by raising errors or returning error messages. ```Ruby require "json-schema" schema = { "type" => "object", "required" => ["a"], "properties" => { "a" => {"type" => "integer"} } } # # validate ruby objects against a ruby schema # # => true JSON::Validator.validate(schema, { "a" => 5 }) # => false JSON::Validator.validate(schema, {}) # # validate a json string against a json schema file # require "json" File.write("schema.json", JSON.dump(schema)) # => true JSON::Validator.validate('schema.json', '{ "a": 5 }') # # raise an error when validation fails # # => "The property '#/a' of type String did not match the following type: integer" begin JSON::Validator.validate!(schema, { "a" => "taco" }) rescue JSON::Schema::ValidationError => e e.message end # # return an array of error messages when validation fails # ``` -------------------------------- ### Basic JSON Schema Validation in Ruby Source: https://github.com/voxpupuli/json-schema/blob/master/README.md Demonstrates a basic validation call using `JSON::Validator.validate`. It attempts to validate an empty data object against a schema defined in 'schema.json', expecting a false result. ```Ruby JSON::Validator.validate("schema.json", {}) # => false ``` -------------------------------- ### Configuring Custom URI Reader for JSON Schema Validation in Ruby Source: https://github.com/voxpupuli/json-schema/blob/master/README.md This snippet demonstrates how to configure a custom `JSON::Schema::Reader` to restrict accepted URIs for schema validation. It uses a `proc` to ensure only URIs from 'my-website.com' are allowed, enhancing security or data source control. The configured reader is then passed to `JSON::Validator.validate`. ```Ruby schema_reader = JSON::Schema::Reader.new( :accept_uri => proc { |uri| uri.host == 'my-website.com' } ) JSON::Validator.validate(some_schema, some_object, :schema_reader => schema_reader) ``` -------------------------------- ### Validating Against a Schema Fragment in Ruby Source: https://github.com/voxpupuli/json-schema/blob/master/README.md This snippet demonstrates using the `:fragment` option to validate a JSON object against a specific part of a larger schema. By specifying a JSON Pointer fragment, only that sub-schema is applied, allowing for more granular validation without redefining the entire schema. ```Ruby JSON::Validator.validate(schema, { "x" => 1 }, :fragment => "#/properties/b") JSON::Validator.validate(schema, { "x" => 1 }) ``` -------------------------------- ### Retrieving Validation Errors as Objects in Ruby Source: https://github.com/voxpupuli/json-schema/blob/master/README.md This snippet demonstrates how to use the `:errors_as_objects` option with `fully_validate` to receive detailed error information as a hash instead of a simple string message. This provides structured data about the failed attribute, fragment, and schema URI, which is useful for programmatic error handling. ```Ruby JSON::Validator.fully_validate(schema, { "a" => "taco" }, :errors_as_objects => true) ``` -------------------------------- ### Performing Basic JSON Validation with Ruby Source: https://github.com/voxpupuli/json-schema/blob/master/README.md This snippet demonstrates a basic full validation of a JSON object against a schema. It shows how `fully_validate` returns an array of error messages when the data does not conform to the schema, specifically when a string is provided where an integer is expected. ```Ruby JSON::Validator.fully_validate(schema, { "a" => "taco" }) ``` -------------------------------- ### Controlling Data Parsing for Validation in Ruby Source: https://github.com/voxpupuli/json-schema/blob/master/README.md This snippet illustrates the `:parse_data` option. When set to `false`, it requires the input JSON to be an already parsed Ruby object (e.g., a Hash). This prevents the validator from attempting to parse a JSON string, URI, or file path, which can be useful when the data is already in memory as a Ruby object. ```Ruby JSON::Validator.validate(schema, { "a" => 1 }, :parse_data => false) JSON::Validator.validate(schema, '{ "a": 1 }', :parse_data => false) ``` -------------------------------- ### Validating a JSON Schema Against its Metaschema in Ruby Source: https://github.com/voxpupuli/json-schema/blob/master/README.md Demonstrates how to validate a JSON schema itself against the appropriate JSON Schema standard metaschema. It retrieves the 'draft4' metaschema using `JSON::Validator.validator_for_name` and then uses `JSON::Validator.validate` to check if the provided schema conforms to the standard. ```Ruby require "json-schema" schema = { "type" => "object", "properties" => { "a" => {"type" => "integer"} } } metaschema = JSON::Validator.validator_for_name("draft4").metaschema # => true JSON::Validator.validate(metaschema, schema) ``` -------------------------------- ### Inserting Default Values During Validation in Ruby Source: https://github.com/voxpupuli/json-schema/blob/master/README.md This snippet shows how the `:insert_defaults` option automatically populates missing properties in the JSON data with their default values defined in the schema before validation. This can be useful for ensuring data completeness and successful validation when optional fields have defaults. ```Ruby JSON::Validator.validate(schema, {}, :insert_defaults => true) JSON::Validator.validate(schema, {}) ``` -------------------------------- ### Validating Raw JSON Text in Ruby Source: https://github.com/voxpupuli/json-schema/blob/master/README.md This snippet shows how the `:json` option forces the validator to expect the input data as an unparsed JSON string. This is useful when you have raw JSON text and want the validator to handle the parsing internally, throwing an error if a Ruby hash or other type is provided instead. ```Ruby JSON::Validator.validate(schema, '{ "a": 1 }', :json => true) begin JSON::Validator.validate(schema, { "a" => 1 }, :json => true) rescue TypeError => e e.message end ``` -------------------------------- ### Clearing Schema Cache After Validation in Ruby Source: https://github.com/voxpupuli/json-schema/blob/master/README.md This snippet illustrates the `:clear_cache` option, which, when set to `true`, clears the internal schema cache after validation. This is important in scenarios where schemas might change frequently or when memory management requires explicit cache invalidation, preventing the use of stale cached schemas. ```Ruby File.write("schema.json", v2_schema.to_json) JSON::Validator.validate("schema.json", {}) File.write("schema.json", schema.to_json) JSON::Validator.validate("schema.json", {}, :clear_cache => true) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.