Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON data validation under JSON-schema

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?

like image 860
Eduardo Mello Avatar asked Nov 21 '13 18:11

Eduardo Mello


People also ask

Does JSON have schema validation?

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.

How does JSON Schema validation work?

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.

How does JSON Schema validate in Rest assured?

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.


1 Answers

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
like image 111
Konrad Reiche Avatar answered Sep 18 '22 08:09

Konrad Reiche