2013-11-21 15 views
5

我想用ruby gem json-schema验证一些json数据。在JSON模式下的JSON数据验证

我有以下模式:

{ 
"$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"]  
} 

及以下JSON数据:

{ 
"name": "John Doe", 
"e-mail": "[email protected]", 
"username": "johndoe" 
} 

和JSON :: Validator.validate,用这个数据作为输入,返回true。

不应该是错误的,因为架构上没有指定用户名?

回答

6

你需要在你的JSON模式来定义additionalProperties并将其设置为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 
} 

现在验证应该返回false预期:

require 'json' 
require 'json-schema' 

schema = JSON.load('...') 
data = JSON.load('...') 
JSON::Validator.validate(schema, data) 
# => false 
+0

请注意,这限制了您的扩展能力格式,因为所有额外的属性都被禁止。 – cloudfeet

+1

@cloudfeet在这种情况下,你也扩展了模式。 –

+1

我的意思是扩展而不修改原始类 - 例如某些第三方扩展了你的格式,或者你扩展了你公司中一个脾气暴躁,顽强的人写的格式。 – cloudfeet