我一直在努力弄清楚如何获得一个嵌套在定义中的模式$ref
。如果我对 jsonschema 对象进行硬编码,我没有任何问题,但是我需要使用嵌套模式并且我不知道里面有schema=
什么validate(json{"name": "lucky","uid": -1, schema='what do I put here to reference the ref schema?')
?
这是我用来隔离和测试功能的代码。
import jsonschema
from jsonschema import validate
schemas = {
"$schema": "http://json-schema.org/draft-07/schema#",
# "$id": "http://example.com",
"definitions": {
# base schema
"uid": {
"$id": "#uid",
"type": "integer",
"minimum": 1
},
# extended schema
"user_record_with_ref": {
"$id": "#user_record_with_ref",
"type": "object",
"properties": {
"name": {"type": "string"},
"uid": {
"allOf": [{"$ref": "#uid"}]
}
}
}
}
}
user_record_no_ref = {
"type": "object",
"properties": {
"name": {"type": "string"},
"uid": {"type": "integer", "minimum": 1}
}
}
# I'd prefer that validation fails to prove the I am validating properly.
user_record_object = {"name": "lucky", "uid": -1}
# It is simple to validate a schema that does not use references.
def test_no_ref():
try:
validate(instance=user_record_object, schema=user_record_no_ref)
except jsonschema.exceptions.ValidationError as e:
return f'JSON Error {e}', 400
return 'yay no problems'
def test_with_ref():
try:
# I want to use 'schema=user_record_with_ref' but I don't know how to access it.
validate(instance=user_record_object, schema="")
except jsonschema.exceptions.ValidationError as e:
return f'JSON Error {e}', 400
return 'yay no problems'
# Testing
print(test_no_ref())
print(test_with_ref())
我已经尝试过 schemas['definitions']['user_record_with_ref'] 但这根本不起作用。也许这需要一个 ref 解析器?我认为它不会,因为子模式位于单个模式块内。任何帮助将不胜感激。