我有一个非常简单的代码来验证Json模式:
from jsonschema import validate
schema = {"type" : "object","properties" : {"command":{"type" : "string"}},"required": ["command"]}
request= {"command":12}
try:
jsonschema.validate(request, schema)
except jsonschema.ValidationError as e:
print e.message
except jsonschema.SchemaError as e:
print e
我得到了;
Traceback (most recent call last):
File "./json_validator.py", line 8, in <module>
except jsonschema.ValidationError as e:
NameError: name 'jsonschema' is not defined
有什么想法吗?
答案 0 :(得分:4)
如果您导入
from jsonschema import validate
模块validate
中的 jsonschema
将在您当前的模块中提供。您必须将其用作validate
而不是jsonschema.validate
。
from jsonschema import validate
schema = {"type" : "object","properties" : {"command":{"type" : "string"}},"required": ["command"]}
request= {"command":12}
try:
validate(request, schema)
except jsonschema.ValidationError as e:
print e.message
except jsonschema.SchemaError as e:
print e
您的代码也缺少例外的导入:
from jsonschema import validate, ValidationError, SchemaError