【问题标题】:jsonschema.validate() not validating type from schemajsonschema.validate() 不验证模式中的类型
【发布时间】:2018-12-05 15:07:44
【问题描述】:

我不确定我是否读错了 jsonschema 的文档,但是据我所知,这个包应该允许我使用 jsonschema.validate() 检查 JSON 对象是否符合指定的模式。下面的代码没有告诉我"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)

是我遗漏了什么还是应该这样工作?

任何帮助将不胜感激,谢谢。

【问题讨论】:

    标签: python json jsonschema python-jsonschema


    【解决方案1】:

    您的架构不是有效的架构。您需要将这些声明为properties,并且您使用的required 错误(除非您在draft-03 上,此时这不太可能)。这是您想要的架构。

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

    【讨论】:

      猜你喜欢
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-04
      • 2020-03-15
      • 2012-01-26
      • 1970-01-01
      • 2023-03-11
      相关资源
      最近更新 更多