jsonschema-具有静态属性的动态属性
我有一个模式来验证json 对于某些属性,我需要它们具有特定类型的值jsonschema-具有静态属性的动态属性,json,jsonschema,Json,Jsonschema,我有一个模式来验证json 对于某些属性,我需要它们具有特定类型的值 如果“attr”属性为“a”,则“val”属性应为“integer” 如果“attr”属性为“x”,则“val”属性应为“boolean” 如果“attr”属性为“b”,则“val”属性应为带有 格式“ipv4” 等等 这一点,我可以用one off来定义。对于所有其他的“attr”属性,我需要将它们设置为特定的格式,有点像一个包罗万象的格式,“val”属性设置为“string” 若“attr”匹配模式,那个么“val”
- 如果“attr”属性为“a”,则“val”属性应为“integer”
- 如果“attr”属性为“x”,则“val”属性应为“boolean”
- 如果“attr”属性为“b”,则“val”属性应为带有 格式“ipv4”
- 若“attr”匹配模式,那个么“val”属性应该是“string”
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"name": {
"title": "name",
"type": "string"
},
"attribute": {
"title": "attributes",
"type": "object",
"$ref": "#/definitions/expr",
}
},
"definitions": {
"expr": {
"properties": {
"attr": {
"title": "attribute"
},
"val": {
"title": "val"
}
},
"required": ["val", "attr"],
"oneOf": [
{
"properties": {
"attr": {"enum": ["a","b"]},
"val": {"type": "integer"}
}
},
{
"properties": {
"attr": {"enum": ["x"]},
"val": {"type": "boolean"}
}
},
{
"properties": {
"attr": {"pattern": "^[-A-Za-z0-9_]*$", "maxLength": 255},
"val": {"type": "string"}
}
}
]
}
},
"additionalProperties": false,
"required": [
"name",
"attribute"
]
}
问题是我试图限制其值类型的属性也与catchall格式匹配。因此,当我期望一个整数值时,它将传递字符串值
例如:
下面的json将根据oneOff的第一项传递模式
{
"name": "shouldpass",
"attribute": {
"attr": "a",
"val": 1
}
}
下面的json将根据oneOff的最后一项传递
{
"name": "shouldpass2",
"attribute": {
"attr": "h",
"val": "asd"
}
}
{
"name": "shouldfail",
"attribute": {
"attr": "a",
"val": "string"
}
}
基于oneOff的第一项,下面的json应该失败,但它也在传递,因为它与oneOff的最后一项匹配
{
"name": "shouldpass2",
"attribute": {
"attr": "h",
"val": "asd"
}
}
{
"name": "shouldfail",
"attribute": {
"attr": "a",
"val": "string"
}
}
如何实现这一点?上一个子模式中的attr模式可以是:
{
"pattern": "^[-A-Za-z0-9_]*$",
"not": { "enum": ["a", "b", "x"] },
"maxLength": 255
}
或者,您可以使用下一个JSON模式版本建议中的“switch”关键字,而不是“oneOf”:
它是在Ajv中实现的(我是作者)