【发布时间】:2019-10-12 14:57:11
【问题描述】:
我之前写过一个 JSON 模式,但现在,当我试图让它更高级时,我卡住了。
(我对 cmets 中的“良好实践”提示持开放态度)
($id 是可选的吗?为了简单起见,我应该在示例代码中删除它吗?)
目标:
我正在尝试使用递归使用的对象定义 (example_obj) 创建模式。此对象可能只有 1 个参数(or 或 and 或 value)。但在 json 的根目录中,我想添加 1 个附加属性。
json 模式
{
"definitions": {
"example_obj": {
"$id": "#/definitions/example_obj",
"type": "object",
"maxProperties": 1,
"properties": {
"or": {
"$id": "#/definitions/example_obj/properties/or",
"type": "array",
"items": {
"$id": "#/definitions/example_obj/properties/or/items",
"$ref": "#/definitions/example_obj"
}
},
"and": {
"$id": "#/definitions/example_obj/properties/and",
"type": "array",
"items": {
"$id": "#/definitions/example_obj/properties/and/items",
"$ref": "#/definitions/example_obj"
}
},
"value": {
"$id": "#/definitions/example_obj/properties/value",
"type": "string"
}
}
}
},
"type": "object",
"title": "The Root Schema",
"required": ["filter_version"],
"allOf": [
{
"$ref": "#/definitions/example_obj"
},
{
"properties": {
"filter_version": {
"$id": "#/properties/filter_version",
"type": "string",
"pattern": "^([0-9]+\\.[0-9]+)$"
}
}
}
]
}
我要通过验证的json:
{
"filter_version": "1.0",
"or": [
{
"and": [
{
"value": "subject"
}
]
},
{
"or": [
{
"value": "another subject"
}
]
}
]
}
问题:
当我尝试为根定义扩展 example_obj 时,它似乎失败了,因为 example_obj 对象在设计上不允许超过 1 个属性。
换句话说,似乎每次检查我添加到example_obj 的参数数量也是在附加属性(即filter_version)上执行的。
有谁知道在哪里放置“exactly 1 argument”的检查,这样就不会在root 对象上进行评估?
尝试:
我尝试使用不同的方法来确定example_obj 的要求,但没有成功。就像将"maxProperties": 1 替换为:
"oneOf": [
{
"required": [
"or"
]
},
{
"required": [
"and"
]
},
{
"required": [
"where"
]
},
{
"required": [
"where not"
]
}
],
提前感谢您的帮助!
使用 online schema validator 检查我的架构。
(最后我需要在 Python 中验证它,以防万一)
【问题讨论】:
标签: jsonschema json-schema-validator python-jsonschema