你如何导入jsonschema?
How do you import jsonschema?
我有这个非常简单的代码来验证 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
有什么想法吗?
如果你导入 like
from jsonschema import validate
来自模块 jsonschema
的 validate
将在您当前的模块中可用。您必须将其用作 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
我有这个非常简单的代码来验证 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
有什么想法吗?
如果你导入 like
from jsonschema import validate
来自模块 jsonschema
的 validate
将在您当前的模块中可用。您必须将其用作 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