你如何导入jsonschema?

时间:2015-02-20 11:09:57

标签: python python-import

我有一个非常简单的代码来验证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

有什么想法吗?

1 个答案:

答案 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