← Back
json json-schema ruby

JSON validation with ruby

I have to deal with json files provided by a user, so I want to make sure the JSON structure is correct. JSON schema validators are quite popular in JS world, but this was the first time I tried them in Ruby.

The steps are:

To create the json-schema I tend to use a tool that creates a schema from an example JSON file, like this one. It's not perfect, but provides a good starting point.

To parse JSON I used the ruby's json standard library.

To validate the JSON against the schema I used https://github.com/ruby-json-schema/json-schema gem.

Show me the code:

require 'json'
require 'json-schema'

SCHEMA = {
type: 'object',
properties: {
...
}
}

begin
contents = JSON.parse(raw)
errors = JSON::Validator.fully_validate(SCHEMA, contents)
rescue JSON::ParserError
errors = ['Invalid JSON']
end

🖖