我正在尝试将patternProperties与模式匹配,例如,这里是jsonschema文本:
drawLine
}
这是我输入的json文件:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"definitions": {
"fabric_id": {
"enum": [
"ADMIN",
"COPPER",
"NETWORK",
"STORAGE",
"STORAGE2",
"TENANT"
]
},
"fabrics": {
"additionalProperties": false,
"patternProperties": {
"[A-Z0-9-]*": {
"additionalProperties": false,
"properties": {
"description": {
"type": "string"
},
"fabric_id": {
"$ref": "#/definitions/fabric_id",
"type": "string"
}
},
"required": [
"description",
"fabric_id"
],
"type": "object"
}
},
"type": "object"
}
},
"description": "fabrics spec",
"properties": {
"fabrics": {
"$ref": "#/definitions/fabrics"
}
},
"required": [
"fabrics"
],
"title": "network fabric",
"type": "object"
}
我无法弄清楚如何针对fabric_id枚举验证patternProperty?模式对象中包含fabric_id,并且能够在定义部分中引用fabric_id枚举。我想为" [A-z0-9 - ] *"提供相同的$ ref。模式,但我不能让它工作。这可能吗?
答案 0 :(得分:1)
可悲的是,我认为JSON Schema的草案4不可能实现这一点。
如果您可以升级到6或7(+),则可以实现此目的。
propertyNames
:https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.5.8
如果实例是对象,则此关键字将验证实例中的每个属性名称是否针对提供的架构进行验证。请注意,架构正在测试的属性名称将始终为字符串。
可以在https://github.com/json-schema-org/json-schema-org.github.io/issues/77
找到如何使用它的示例...
"fooProperties": {
"propertyNames": {
"$comment": "Need to anyOf these or else the enum and pattern conflict",
"anyOf": [
{"enum": ["foo1", "foo2"]},
{"pattern": "foo[A-Z][a-z0-9]*"}
]
}
},
...
抱歉,我没有时间更新您的架构以遵循这一点,但希望我已经充分解释了这一点,以便您进行调整。
如果您无法迁移到draft-4之外......那么您必须在JSON Schema之外手动执行该验证方面。
答案 1 :(得分:1)
这种模式确实是你能做的最好的。它唯一能做的就是限制属性名称以匹配" fabric_id"的值。不幸的是,JSON Schema无法做到这一点。
{
"$schema": "http://json-schema.org/draft-06/schema#",
"type": "object",
"properties": {
"fabrics": { "$ref": "#/definitions/fabrics" }
},
"required": ["fabrics"],
"definitions": {
"fabric_id": {
"enum": ["ADMIN", "COPPER", "NETWORK"]
},
"fabrics": {
"type": "object",
"propertyNames": { "$ref": "#/definitions/fabric_id" },
"patternProperties": {
".*": {
"type": "object",
"properties": {
"description": { "type": "string" },
"fabric_id": { "$ref": "#/definitions/fabric_id" }
},
"required": ["description", "fabric_id"]
}
}
}
}
}