所以我有一个 JSON 架构,其中 additionalProperties
规则设置为 false
之类的。
{
"type": "object",
"properties": {
"metadata": {
"type": "object",
"properties": {
"a": {
"type": "string"
},
"b": {
"type": "string"
},
"c": {
"type": "string"
}
}
},
"street_type": {
"type": "string",
"enum": [
"Street",
"Avenue",
"Boulevard"
]
}
},
"additionalProperties": false
}
和像
这样的有效载荷{
"metadata": {
"a": "aa",
"b": "bb",
"c": "cc",
"d": "dd"
}
}
如果我希望我的 JSON 模式解析器/验证器通过验证,我正在使用的 JSON 模式解析器 com.github.fge.jsonschema.main.JsonSchema
通过了验证 metadata/d
不存在于 additionalProperties
设置为 false
的架构中,
这是非常具有误导性的,有人可以指导我正确的方向吗。
additionalProperties
JSON 架构定义是否仅适用于顶级字段而不适用于任何嵌套级别字段?
最佳答案
Is the additionalProperties JSON schema definition only applies to top-level fields and not to any nested level fields?
不,只要它在描述对象的模式中,您就应该能够将它放在您需要的任何级别。在你的情况下,你只是把它放在错误的地方。这应该有效:
{
"type": "object",
"properties": {
"metadata": {
"type": "object",
"properties": {
"a": {
"type": "string"
},
"b": {
"type": "string"
},
"c": {
"type": "string"
}
},
"additionalProperties": false
},
"street_type": {
"type": "string",
"enum": [
"Street",
"Avenue",
"Boulevard"
]
}
}
}
假设您想按原样验证以下对象:
{
a: {
b: {
c: {
d: 42
}
}
}
}
它的一个有效模式是:
{
"type": "object",
"additionalProperties": false,
"properties": {
"a": {
"type": "object",
"additionalProperties": false,
"properties": {
"b": {
"type": "object",
"additionalProperties": false,
"properties": {
"c": {
"type": "object",
"additionalProperties": false,
"properties": {
"d": {
"const": 42
}
}
}
}
}
}
}
}
}
上面的架构非常冗长,但此处仅供说明之用。您应该能够通过使用 $ref
并将模式组合在一起使其更简洁。
关于json - `additionalProperties` JSON 架构中的规则未应用于嵌套级别属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53770325/