简体   繁体   English

jsonschema.validate()未验证架构中的类型

[英]jsonschema.validate() not validating type from schema

I'm not sure if I'm reading the docs for jsonschema wrong, however from what I can tell, this package should allow me to check that a JSON object conforms to a specified schema using jsonschema.validate(). 我不确定我是否读错了jsonschema的文档,但是据我所知,此程序包应允许我使用jsonschema.validate()检查JSON对象是否符合指定的架构。 The following code doesn't tell me that "age" should be a number. 以下代码没有告诉我"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)

Am I missing something or should this be working? 我是否缺少某些东西,还是应该正常工作?

Any help would be much appreciated, thanks. 任何帮助将不胜感激,谢谢。

Your schema is not a valid schema. 您的架构不是有效的架构。 You need to declare these as properties and you are using required wrong (unless you are on draft-03 which is pretty unlikely at this point). 您需要将它们声明为properties ,并且使用了required错误信息(除非您使用的是draft-03,这在目前还不太可能)。 Here's the schema you want. 这是您想要的架构。

{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "age": { "type": "number" }
  },
  "required": ["name", "age"]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM