【发布时间】:2018-03-20 19:37:24
【问题描述】:
我需要验证一个始终具有 2 个属性的 json 对象:
- 类型
- 姓名
类型可以是“A”、“B”或“C”,
当 type 为 "A" 时,属性 "foo" 也是必需的,不允许有其他属性。
好的:
{
"type": "A",
"name": "a",
"foo": "a",
}
不行:
{
"type": "A",
"name": "a",
"foo": "a",
"lol": "a"
}
当 type 为“B”时,属性“bar”是必需的,不允许有额外的属性。
当类型为“C”时,属性“bar”是必需的,并且可选地也可以存在“zen”属性。
好的:
{
"type": "C",
"name": "a",
"bar": "a",
"zen": "a"
}
{
"type": "C",
"name": "a",
"bar": "a",
}
不行:
{
"type": "C",
"name": "a",
"bar": "a",
"lol": "a"
}
不幸的是,这个question 的出色答案部分涵盖了我的情况,但是我没有设法构建一个适合我的 jsonschema。
编辑:
这是我尝试过的。
{
"$schema": "http://json-schema.org/draft-04/schema",
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["A", "B", "C"]
},
"name": {"type": "string"},
"foo": {"type": "string"},
"bar": {"type": "string"},
"zen": {"type": "string"},
},
"anyOf": [
{
"properties": {"type": {"enum": ["A"]}},
"required": ["foo"],
},
{
"properties": {"type": {"enum": ["B"]}},
"required": ["bar"],
},
{
"properties": {"type": {"enum": ["C"]}},
"required": ["bar"],
},
]
}
我的问题是在“anyOf”中的对象内将字段“additionalProperties”设置为 false 不会给我预期的结果。
例如,以下 json 通过验证,尽管它具有附加属性“lol”
{
"type": "A",
"name": "a",
"foo": "a",
"lol": "a"
}
【问题讨论】:
-
我更新了我的帖子以包含我尝试过的示例以及此解决方案对我不起作用的原因
标签: properties conditional optional jsonschema required