I'm trying to validate some json data with ruby gem json-schema.
I have the following schema:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "User",
"description": "A User",
"type": "object",
"properties": {
"name": {
"description": "The user name",
"type": "string"
},
"e-mail": {
"description": "The user e-mail",
"type": "string"
}
},
"required": ["name", "e-mail"]
}
and the following json data:
{
"name": "John Doe",
"e-mail": "[email protected]",
"username": "johndoe"
}
And JSON::Validator.validate, using this data as input, returns true.
Shouldn't it be false since username is not specified on the schema?
JSON Schema is a powerful tool. It enables you to validate your JSON structure and make sure it meets the required API. You can create a schema as complex and nested as you need, all you need are the requirements. You can add it to your code as an additional test or in run-time.
JSON Schema Validation: The JSON Schema Validation specification is the document that defines the valid ways to define validation constraints. This document also defines a set of keywords that can be used to specify validations for a JSON API. In the examples that follow, we'll be using some of these keywords.
Here, we have to add the JSON body whose scheme we want to validate. Then click on the Generate Schema button. Then the corresponding scheme for the JSON gets generated at the bottom of the page. Let us create a JSON file, say schema.
You need to define additionalProperties
in your JSON Schema and set it to false
:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "User",
"description": "A User",
"type": "object",
"properties": {
"name": {
"description": "The user name",
"type": "string"
},
"e-mail": {
"description": "The user e-mail",
"type": "string"
}
},
"required": ["name", "e-mail"],
"additionalProperties": false
}
Now the validation should return false
as expected:
require 'json'
require 'json-schema'
schema = JSON.load('...')
data = JSON.load('...')
JSON::Validator.validate(schema, data)
# => false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With