質問

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": "john@doe.com",
"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?

役に立ちましたか?

解決

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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top