0

我不确定我是否在阅读 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)

我错过了什么或者这应该有效吗?

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

4

1 回答 1

1

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). Here's the schema you want.

{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "age": { "type": "number" }
  },
  "required": ["name", "age"]
}
于 2018-12-07T19:16:53.200 回答