JSON模式的if/then/else属性,可以是一个对象或null基于另一个属性值



我有一个属性,它将基于另一个属性的值是一个对象或null。我试图添加这个新的检查到我的模式使用if/then/else。这是为了在Postman中进行AJV验证,如果这是相关的。

例如,以下示例有效负载

{
"topObj": {
"subItem1": "2021-09-12",
"subItem2": "2021-09-21",
"ineligibleReason": "",
"myObject": {
"subObject1": true,
"subObject2": ""
}
}
}

如果ineligiblerreason是一个空字符串,那么subObject应该是一个对象。如果ineligiblerreason不是空字符串,那么subObject应该为空,如下表所示:

tbody> <<tr>
ineligibleReason valuemyObject valueschema valid?
">对象
">
"任何value"
"任何value"对象

错误消息指向问题。/properties/required声明了一个名为"required"的属性,然后该属性下的值需要是一个模式(对象或布尔值)。所以你需要提高这个要求与"属性"相邻,而不是位于"属性"之下。

Ryan Miller对json-schema Slack的回答。一个稍微不同的策略,然后我尝试,但更简单和工作!

{
"type": "object",
"properties": {
"topObj": {
"type": "object",
"properties": {
"subItem1":         { "type": "string" },
"subItem2":         { "type": "string" },
"ineligibleReason": { "type": "string" },
"myObject":         {
"type": ["object", "null"],
"$comment": "'properties', 'required', and 'additionalProperties' only make assertions when the instance is an object.",
"properties": {
"subObject1": { "type": "boolean" },
"subObject2": { "type": "string"  }
},
"required": ["subObject1", "subObject2"],
"additionalProperties": false
}
},
"required": ["subItem1", "subItem2", "ineligibleReason", "myObject"],
"additionalProperties": false,
"if": {
"$comment": "Is an ineligibleReason defined?",
"properties": {
"ineligibleReason": {"minLength": 1}
}
},
"then": {
"$comment": "Then 'myObject' must be null.",
"properties": {
"myObject": {"type": "null"}
}
}
}
},
"required": ["topObj"],
"additionalProperties": false
}

相关内容

最新更新