我在我的Django应用程序中使用jsonschema库(http://python-jsonschema.readthedocs.io/en/latest/validate/)进行服务器端验证,并尝试使用提供的架构对JSON进行服务器端验证。但是,我得到了架构"在任何给定架构下无效的错误。"
这是我的架构(" scores_ap"属性"架构"类的属性):
class JSONListFieldSchemas:
"""
Schemas for all the JSON List Fields.
Each key represents the field name.
"""
schema = {
"scores_ap": {
"$schema": "http://json-schema.org/draft-06/schema#",
"title": "AP Scores",
"type": "array",
"items": {
"type": "object",
"properties": {
"exam": {
"type": "string"
},
"score": {
"type": "integer",
"minimum": "1",
"maximum": "5",
"required": False
}
}
}
}
}
我收到此错误:
{'type': 'object', 'properties': {'score': {'minimum': '1', 'type': 'integer', 'ma
ximum': '5', 'required': False}, 'exam': {'type': 'string'}}} is not valid under a
ny of the given schemas
Failed validating u'anyOf' in schema[u'properties'][u'items']:
{u'anyOf': [{u'$ref': u'#'}, {u'$ref': u'#/definitions/schemaArray'}],
u'default': {}}
On instance[u'items']:
{'properties': {'exam': {'type': 'string'},
'score': {'maximum': '5',
'minimum': '1',
'required': False,
'type': 'integer'}},
'type': 'object'}
我使用的架构如下:
from jsonschema import validate
from .schemas import JSONListFieldSchemas
raw_value = [{"score": 1, "exam": "a"}]
validate(raw_value, JSONListFieldSchemas.schema['scores_ap'])
答案 0 :(得分:1)
从草案4开始,"必需"应该是一个数组而不是布尔值。 另外"最大"和"最低"应该是整数,而不是字符串。
试试这样:
{
"$schema": "http://json-schema.org/draft-06/schema#",
"title": "AP Scores",
"type": "array",
"items": {
"type": "object",
"properties": {
"exam": {
"type": "string"
},
"score": {
"type": "integer",
"minimum": 1,
"maximum": 5
}
},
"required": [
"exam"
]
}
}