我想定义一个带有customProperty的JsonSchema,此属性遵循一些规则,因此为了验证那些规则,我需要定义一个将对其进行验证的JsonSchema。
到目前为止,我已经设法正确地描述了它,但是它仅适用于第一级属性,我希望它是递归的...
从我的理解来看,它应该可以工作,我可能犯了一个我看不到的错误,并且现在我不知道这是错误,不可能还是愚蠢的……
我相信重新定义每种类型都是可能的,但是显然我不愿意。
这是我要验证的Json的示例
{
"title": "TheObject",
"type": "object",
"properties": {
"aString": {
"type": "string",
"myCustomProperty": {}
},
"anObjet": {
"type": "object",
"myCustomProperty": {},
"properties": {
"anotherObject": {
"type": "object",
"myCustomProperty": {}, //if this line is removed it still validates wich I don't want
"properties": {}
}
}
}
}
}
这是我到目前为止完成的JsonSchema:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"title": {"type": "string"},
"type": {"type": "string","enum": ["object"]},
"properties": {
"type": "object",
"patternProperties": {
".*": {
"$ref": "#/definitions/Field"
}
}
}
},
"definitions": {
"Field": {
"type": "object",
"properties": {
"type": {
"type": "string"
},
"myCustomProperty": {
"$ref": "#/definitions/myCustomProperty"
},
"patternProperties": {
"^(?!myCustomProperty).*": {
"$ref": "#/definitions/Field"
}
}
},
"required": [
"type",
"myCustomProperty"
]
},
"myCustomProperty": {
//Some rules
}
}
}
答案 0 :(得分:0)
我找到了解决方案,毕竟我离我想要的不远。
在“字段”的定义中,我描述的是一个定义对象的对象,但缺少“属性”字段。我必须在其中放置递归引用。
正确的jsonSchema如下:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"title": {
"type": "string"
},
"type": {
"type": "string",
"enum": [
"object"
]
},
"properties": {
"type": "object",
"patternProperties": {
".*": {
"$ref": "#/definitions/Field"
}
}
}
},
"definitions": {
"Field": {
"type": "object",
"properties": {
"type": {
"type": "string"
},
"myCustomProperty": {
"$ref": "#/definitions/myCustomProperty"
},
"properties": { <==================== here
"type": "object",
"patternProperties": {
".*": {
"$ref": "#/definitions/Field"
}
}
}
},
"required": [
"type",
"myCustomProperty"
]
},
"myCustomProperty": {/*rules*/}
}
}
到目前为止,它可以正常工作,但是如果有人有更优雅的建议,请分享!