jSonschema如果枚举属性是几个枚举值之一,则需要x,否则所有其他值都需要y
我目前有一个 JsonSchema,它有一个包含 12 个值的枚举字段,假设同一对象中还有两个常规字符串字段,即字段 X 和 Y。如果枚举字段的值是允许的 12 个枚举值中的 3 个中的 1 个,那么我想让 X 成为必需的,否则如果它是其他 9 个枚举值中的任何一个,则需要 Y。
例如:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"efield": {
"type": "string",
"enum": ["n1", "n2", "...", "n12"]
},
"x": {
"type": "string"
},
"y": {
"type": "string"
}
},
"if": {
"properties": { "efield": { "in": ["n1", "n2", "n3"] } }
},
"then": {
"required": ["x"]
},
"else": {
"required": ["y"]
}
}
这就是理想情况下的样子,尽管我知道“in”关键字不存在,但目前我能想到的最接近的方法就是使用“allOf”并为每个枚举值列出 12 个 if 语句,根据每个值需要哪个字段,这感觉有点夸张/不优雅。
我还查看了“oneOf”并有两个子模式,其中一个“efield”具有前 3 个枚举并且需要 x,另一个子模式其中 efield 有其他 9 个枚举并且需要 y,但验证会抱怨枚举,例如,如果我尝试使用 9 个枚举的第二个模式中的枚举值,它会抱怨该值不在具有 3 个值的第一个模式中...
是否有我遗漏的任何关键字,或者任何执行这个用例的优雅方式?谢谢。
I currently have a JsonSchema which has an enum field with 12 values, and lets say two other regular string fields in the same object, fields X and Y. If the value for the enum field is 1 of 3 out of the 12 enum values allowed, then I want to make X required, else if it's any of the other 9 enum values, then Y is required.
For example:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"efield": {
"type": "string",
"enum": ["n1", "n2", "...", "n12"]
},
"x": {
"type": "string"
},
"y": {
"type": "string"
}
},
"if": {
"properties": { "efield": { "in": ["n1", "n2", "n3"] } }
},
"then": {
"required": ["x"]
},
"else": {
"required": ["y"]
}
}
This is what it would look like idealy, though I know that the "in" keyword doesn't exist, closest I can figure at the moment is just using "allOf" and listing out 12 if statements for each enum value and which field is required based on each value, which feels kind of over the top / inelegant.
I also looked at "oneOf" and having two sub-schemas, one where 'efield' had the first 3 enums and x was required, and the other where efield had the other 9 enums and y required, but validation would complain about the enums, e.g. if I tried using an enum value from the second schema of 9 enums, it would complain that the value isn't in the first schema with the 3 values...
Are there any keywords that I'm missing, or any elegant ways of performing this use case? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需使用
enum
而不是in
关键字,它应该完全没问题:Just use
enum
instead of yourin
keyword and it should be totally fine: