python判断input空值_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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值