我有以下使用JSON模式的用例。我有一个设置的元数据对象。在我们的情况下,设置的类型可以是字符串/实数/整数/布尔值。
在此对象中,我有4个字段:default / minimum / maximum,每个字段定义设置的属性。 现在我要实现的是,当默认值的类型是整数时,最小/最大值也是整数。
到目前为止我提出的模式:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"setting-value": {
"anyOf": [
{
"type": "string"
},
{
"type": "number"
},
{
"type": "boolean"
}
]
},
"setting-meta": {
"type": "object",
"required": [
"name",
"type",
"default"
],
"properties": {
"name": {
"type": "string"
},
"type": {
"type": "string",
"enum": [
"Real",
"Integer",
"Boolean",
"String"
]
},
"minimum": {
"$ref": "#/definitions/setting-value"
},
"maximum": {
"$ref": "#/definitions/setting-value"
},
"default": {
"$ref": "#/definitions/setting-value"
},
"value": {
"$ref": "#/definitions/setting-value"
}
}
}
}
}
在这里#/ definitions / setting-meta可能支持不同的类型。但是,它没有定义,例如,如果TYPE的值等于Real / Integer,则最小值/最大值/默认值/值的类型都应为数字类型。
我将使用以下定义
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$ref": "schema-definition-above.json#/definitions/setting-meta"
}
根据当前架构,以下所有示例均为VALID,但是它们应按照建议的那样有效/无效:
有效的JSon对象:
{
"name": "Enabled",
"type": "Boolean",
"minimum": false,
"maximum": true,
"default": true,
"value": true
}
无效的json对象,最小值/最大值/默认类型不相同:
{
"name": "Enabled",
"type": "Boolean",
"minimum": false,
"maximum": 1,
"default": "value",
"value": true
}
无效的json对象:类型,与值的实际类型不匹配
{
"name": "Enabled",
"unit": "enabled/disabled",
"configId": "Accumulator",
"displayName": "Enable or disable this machine",
"type": "Integer",
"minimum": false,
"maximum": true,
"default": true,
"value": true
}
我的问题: 是否可以将这些依赖项放入JSON模式?到目前为止,我唯一遇到的依赖关系就是属性依赖关系,它指示如果设置了一个属性,则还应该设置另一个属性。
任何帮助将不胜感激。
编辑: 用一些JSON对象扩展了该用例,这些JSON对象应使用引用的架构进行验证或无效。
答案 0 :(得分:1)
为了在有一组已知的可能条件的情况下进行条件验证,应将if/then/else
关键字与allOf
结合使用。
在此架构中,allOf
中的第一个架构定义了您的一般结构和总体要求。如果then
模式成功验证,则第二个模式将应用if
约束。
您将需要为每个条件复制第二个架构。
您可以在https://jsonschema.dev看到此架构(链接已预加载以下架构和示例数据)
(patternProperties
的使用只是节省空间。您可以单独定义每个属性。)
{
"$schema": "http://json-schema.org/draft-07/schema#",
"allOf": [
{
"properties": {
"type": {
"enum": [
"Real",
"Integer",
"Boolean",
"String"
]
}
},
"required": [
"type",
"default",
"name"
]
},
{
"if": {
"properties": {
"type": {
"const": "String"
}
}
},
"then": {
"patternProperties": {
"^(minimum|maximum|default|value)$": {
"type": [
"string"
]
}
}
}
}
]
}