无法在jsonschema中使用日期验证

5

我无法在jsonschema中使用“date”进行类型验证。

myschema = {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object",
    "self": {
        "primary_key": ["email"]
    },
    "properties": {
        "email": {
            "pattern": "[^@]+@[^@]+\.[^@]+"
        },
        "dob": {
            "description": "Date of Birth YYYY-MM-DD",
            "type": "date"
        }
    }
}

当我使用上述模式执行以下代码时:
from jsonschema import validate
validate({ "dob": "2001-02-30"}, myschema)

获得以下错误跟踪:
Unhandled Exception: 'date' is not valid under any of the given schemas

Failed validating 'anyOf' in schema['properties']['properties']['additionalProperties']['properties']['type']:
    {'anyOf': [{'$ref': '#/definitions/simpleTypes'},
               {'items': {'$ref': '#/definitions/simpleTypes'},
                'minItems': 1,
                'type': 'array',
                'uniqueItems': True}]}

On instance['properties']['dob']['type']:
    'date'

更新:看起来日期是一种格式而不是类型,但它仍然让我输入一个无效的日期。我可以清楚地看到在jsonschema代码中它尝试使用datetime进行解析,但我无法在那里触发断点。
1个回答

5
日期应该被用作"格式",而不是"类型":
"dob": {
    "description": "Date of Birth YYYY-MM-DD",
    "type": "string", 
    "format": "date"
}

然后,要检查格式,请使用:
from jsonschema import validate, FormatChecker

validate({"dob": "2001-02-30"}, myschema, format_checker=FormatChecker()) 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接