我正在使用 JSON Schema(
关键问题是字段
谢谢!
jsonschema
)来验证 JSON 记录。以下是一个示例模式。这里只有两种情况,但想象一下类似的场景,如果有一百个类似于这样的情况呈现在面前。{
"$schema": "http://json-schema.org/draft-07/schema#",
"oneOf": [
{
"type": "object",
"required": ["a", "b", "c"],
"properties": {
"a": {"type": "integer", "enum": [0]},
"b": {"type": "integer", "enum": [0, 2, 4, 6, 8]},
"c": {"type": "string", "enum": ["always the same"]}
}
},
{
"type": "object",
"required": ["a", "b", "c"],
"properties": {
"a": {"type": "integer", "enum": [1]},
"b": {"type": "integer", "enum": [1, 3, 5, 7, 9]},
"c": {"type": "string", "enum": ["always the same"]}
}
}
]
}
关键问题是字段
"c"
的重复。我想能够在 "a"
上使用 switch-case,验证相应的 "b"
,但是保持 "c"
始终不变。我不想一百次拼写出 "c"
。这个可能吗?谢谢!
const
而不是只有一个值的枚举。 - Relequestualconst
在draft-06中被添加,供需要知道的人使用。 - Jason DesrosiersanyOf
而不是oneOf
吗?我可以看出anyOf
可以正常工作,因为定义属性只有一个值,但似乎oneOf
会更少出错,因为它要求每个子模式中的a
的值都不同。 - VorticityanyOf
可以通过验证器更有效地进行评估。使用anyOf
,验证器可以在找到匹配项后停止评估anyOf
模式(可以短路)。对于oneOf
,验证器必须检查oneOf
中的每个模式,以确保只有一个模式与之匹配。在这种模式是相互排斥的情况下,oneOf
做了不必要的工作。 - Jason Desrosiersif
/then
/else
,因为它更高效,并且会产生更好的错误消息。https://dev59.com/b1kT5IYBdhLWcg3wXuTP#38781027 - Jason Desrosiers