JSON模式:验证数字或空值

2024-04-27 07:24:22 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法使JSON模式属性成为数字或null

我正在构建一个包含heading属性的API。可以是介于0(包含)和360(不包含)之间的数字,也可以是空值,因此可以输入以下内容:

{"heading": 5}
{"heading": 0}
{"heading": null}
{"heading": 12}
{"heading": 120}
{"heading": null}

以下输入错误:

{"heading": 360}
{"heading": 360.1}
{"heading": -5}
{"heading": false}
{"heading": "X"}
{"heading": 1200}
{"heading": false}

附录:

anyOf显然是正确的答案。为了清晰起见,添加完整的模式。

模式

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object",
    "additionalProperties": false,
    "properties": {
      "heading": {
        "anyOf": [
          {"type": "number"},
          {"type": "null"}
        ]
      }
    }
}

Tags: 答案apijsonfalse属性schematype错误
2条回答

在草案-04中,您将使用anyOf指令:

{
  "anyOf": [
    {
      "type": "number",
      "minimum": 0,
      "maximum": 360,
      "exclusiveMaximum": true
    },
    {
      "type": "null"
    }
  ]
}

您也可以像亚当建议的那样使用“type”:[“number”,“null”],但是我认为任何一个都比较干净(只要您使用draft-04实现),并且将最小和最大声明显式地绑定到数字。

免责声明:我对python实现一无所知,我的答案是关于json模式。

诀窍是使用类型数组。而不是:

"type": "number"

使用:

"type": ["number", "null"]

以下代码强制执行数字或空策略,如果值是数字,则加上数字限制:

from jsonschema import validate
from jsonschema.exceptions import ValidationError
import json

schema=json.loads("""{
  "$schema": "http://json-schema.org/schema#",
  "description": "Schemas for heading: either a number within [0, 360) or null.",
  "title": "Tester for number-or-null schema",
  "properties": {
    "heading": {
      "type": ["number", "null"],
      "exclusiveMinimum": false,
      "exclusiveMaximum": true,
      "minimum": 0,
      "maximum": 360
    }
  }
}""")

inputs = [
{"heading":5}, {"heading":0}, {"heading":360}, {"heading":360.1},
{"heading":-5},{"heading":None},{"heading":False},{"heading":"X"},
json.loads('''{"heading":12}'''),json.loads('''{"heading":120}'''),
json.loads('''{"heading":1200}'''),json.loads('''{"heading":false}'''),
json.loads('''{"heading":null}''')
]

for input in inputs:
    print "%-30s" % json.dumps(input),
    try:
        validate(input, schema)
        print "OK"
    except ValidationError as e:
        print e.message

它给出:

{"heading": 5}                 OK
{"heading": 0}                 OK
{"heading": 360}               360.0 is greater than or equal to the maximum of 360
{"heading": 360.1}             360.1 is greater than or equal to the maximum of 360
{"heading": -5}                -5.0 is less than the minimum of 0
{"heading": null}              OK
{"heading": false}             False is not of type u'number', u'null'
{"heading": "X"}               'X' is not of type u'number', u'null'
{"heading": 12}                OK
{"heading": 120}               OK
{"heading": 1200}              1200.0 is greater than or equal to the maximum of 360
{"heading": false}             False is not of type u'number', u'null'
{"heading": null}              OK

相关问题 更多 >