我有两个不同的JSON响应,每个响应都有不同的字段名,但是都使用jsonschema库使用定义的模式成功地进行了验证
下面是定义的模式
query_schema = {
"type": "object",
"properties" : {
"pltfrm_nm": {"type" : "string"},
"srvr_nm": {"type": "string"},
"db_nm": {"type": "string"},
"tbl_nm": {"type": "string"},
"ip_addr_id": {"type": "string"},
"usr_id": {"type": "string"},
"sql_txt": {"type": "string"},
"timestmp": {"type": "string"},
},
}
以下是两种不同的回答:
input = {'pltfrm_nm': 'p1', 'srvr_nm': 'server', 'db_nm': 'some db', 'tbl_nm': 'some table',
'ip_addr_id': '999.999.9999', 'usr_id': 'my id', 'sql_txt': "sql text here", 'timestmp': 'aaaa)'}
validate(instance=input, schema=query_schema)
input = {'why': 'p1', 'does': 'server', 'this': 'some db', 'still': 'some table',
'validate': '999.999.9999', 'i': 'my id', 'do': "sql text here", 'not': 'aaaa',
'understand': 'hello'}
validate(instance=input, schema=query_schema)
在第二个输入中,我将所有字段命名为不同的,并添加了一个新字段understand
。这两个都不会抛出ValidationError。这是图书馆:https://pypi.org/project/jsonschema/。为什么第二个没有抛出错误
报告指出:
因此,尝试将其添加到
query_schema
中:JSON模式是基于约束的,而不是基于权限的。 空的JSON模式
{}
表示任何内容都是有效的让我们看看关键字^ {< CD2>}添加了什么约束…
https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.5.4
这意味着
properties
对象中键的值的模式适用于JSON实例中的相应值以你为例:
pltfrm_nm
必须是字符串这是上面的讽刺暗示的唯一约束
是否希望未在
proprties
中列出的键会导致验证错误? 如果是这样,您需要指定该事实要在
properties
中定义的属性之外不指定其他属性,需要使用additionalProperties
https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.5.6
我建议您浏览一下我们在http://json-schema.org/understanding-json-schema/和http://json-schema.org/understanding-json-schema/的学习资源,了解JSON模式的介绍
相关问题 更多 >
编程相关推荐