python – 验证ip-address的JSON Schema无法正常工作

无法在一个dict中验证IP地址,文件API.json如下:

{
"$schema": "http://json-schema.org/draft-03/schema#",
"title": "test",
"type": "object",
"properties": {
    "type": {"enum": ["spice", "vnc"]},
    "listen": {
        "type": "string",
        "oneOf": [
            {"format": "ipv4"},
            {"format": "ipv6"}
        ]
    }
},
"additionalProperties": false
}

代码如下:

from jsonschema import Draft3Validator, ValidationError, FormatChecker
import json

if __name__ == '__main__':
    graphics1 = {'type': 'spice', 'listen': '0.0.0.0'}
    graphics2 = {'type': 'vnc', 'listen': '0.0.0.0'}
    graphics3 = {'type': 'abc', 'listen': '0.0.0.0'}
    graphics4 = {'type': 'vnc', 'listen': '777.485.999'}
    graphics5 = {'type': 'vnc', 'listen': 'fe00::0'}
    graphics6 = {'type': 'vnc', 'listen': 'def'}
    graphics7 = {'type': 'vnc', 'listen': 'fe00::0abcdefdefs'}
    s = json.load(open('API.json'))
    validator = Draft3Validator(s, format_checker=FormatChecker())
    for x in range(1, 8):
        try:
            graphics = locals().get('graphics'+str(x))
            validator.validate(graphics)
        except ValidationError:
            print('; '.join(e.message for e in validator.iter_errors(graphics)))

这些印刷品是:

'abc' is not one of [u'spice', u'vnc']

显然,’777.485.999′,’def’和’fe00 :: 0abcdefdefs’不是ip地址,但是测试脚本没有给出关于它们的警告.
我找到了一个文档(http://tools.ietf.org/html/draft-zyp-json-schema-03),它说的是’ip-address’,但不是’ipv4′,但它也不起作用.

[编辑]:
我已经为Draft3Validator添加了FormatChecker(),但它仍然无效.但是当我尝试时,Draft4Validator还可以.在文档中,我没有发现Draft3Valdator在任何地方都不支持format / ip-address,它应该可以工作.

解决方法:

知道了,这不是因为Draft3Validator不支持“format / ip-address”,而是“oneOf”,“allOf”,“anyOf”和“not”.所以API.json应该是:

{
"$schema": "http://json-schema.org/draft-03/schema#",
"title": "test",
"type": "object",
"properties": {
    "type": {"enum": ["spice", "vnc"]},
    "listen": {
        "type": "string",
        "format": "ip-address"
    }
},   
"additionalProperties": false
}

http://json-schema.org/draft-03/schema#http://json-schema.org/draft-04/schema#

上一篇:java – Jackson:json schema引用其他模式,这可以被禁用吗?


下一篇:分治 FFT