【发布时间】:2018-12-05 15:07:44
【问题描述】:
我不确定我是否读错了 jsonschema 的文档,但是据我所知,这个包应该允许我使用 jsonschema.validate() 检查 JSON 对象是否符合指定的模式。下面的代码没有告诉我"age" 应该是一个数字。
import json
import jsonschema
schema = '{"name":{"type":"string","required":true},"age":{"type":"number","required":true}}'
schema = json.loads(schema)
data = '{"name":"Foo","age":"Bar"}'
def json_validator(data):
try:
json.loads(data)
print("Valid Json")
return True
except ValueError as error:
print("Invalid JSON: %s" % error)
return False
def schema_validator(data, schema):
try:
jsonschema.validate(data, schema)
except jsonschema.exceptions.ValidationError as e:
print(e)
except jsonschema.exceptions.SchemaError as e:
print(e)
json_validator(data)
schema_validator(data, schema)
是我遗漏了什么还是应该这样工作?
任何帮助将不胜感激,谢谢。
【问题讨论】:
标签: python json jsonschema python-jsonschema