你如何导入jsonschema?

Mar*_*ois -1 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
Run Code Online (Sandbox Code Playgroud)

我得到了;

Traceback (most recent call last):
  File "./json_validator.py", line 8, in <module>
    except jsonschema.ValidationError as e:
NameError: name 'jsonschema' is not defined
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Kla*_* D. 5

如果你像这样导入

from jsonschema import validate
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

您的代码也缺少异常的导入:

from jsonschema import validate, ValidationError, SchemaError
Run Code Online (Sandbox Code Playgroud)