【发布时间】:2019-10-14 11:06:33
【问题描述】:
这是我的 JSON 架构和 JSON,如下所示,并使用 ajv 验证器来支持 json 规范草案 7。
默认情况下,“科学”对象必须表示为:
//Default science object
{"type": "science", "rule": {"sciencePattern": {}}}
“规则”和“科学模式”必须在哪里。
但是,如果 'sciencePattern' 即将包含其他属性(根据架构),则应启动以下验证:
- 如果存在默认科学对象,则“艺术”对象中的“评分”属性应该是必需的。
- 如果嵌套“得分”数组属性存在于规则中:
{ "type": "science", "rule":{"sciencePattern":{"marks":{"scored":[10]}}} }
那么“艺术”对象中的“得分”属性不应该是必需的。换句话说,如果有人在“arts”对象中指定了“scored”属性,架构验证应该报错,因为“science”对象中有一个“scored”属性可用。
//JSON 模式
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": [
"exam"
],
"properties": {
"exam": {
"type": "array",
"minItems": 1,
"items": {
"anyOf": [
{
"$ref": "#/definitions/science"
},
{
"$ref": "#/definitions/arts"
}
]
}
},
"if": {
"type": "object",
"required": [
"type",
"rule"
],
"properties": {
"type": {
"const": "science"
},
"rule": {
"type": "object",
"required": [
"sciencePattern"
],
"properties": {
"sciencePattern": {
"$ref": "#/definitions/sciencePattern"
}
}
}
}
},
"then": {
"type": "object",
"required": [
"type"
],
"properties": {
"type": {
"const": "arts"
},
"not": {
"required": [
"scored"
]
}
}
}
},
"definitions": {
"sciencePattern": {
"type": "object",
"required": [
"marks"
],
"properties": {
"marks": {
"type": "object",
"required": [
"scored"
],
"properties": {
"scored": {
"type": "array"
}
}
}
}
},
"science": {
"type": "object",
"properties": {
"type": {
"const": "science"
},
"rule": {
"required": [
"sciencePattern"
],
"properties": {
"sciencePattern": {
"$ref": "#/definitions/sciencePattern"
}
}
}
}
},
"arts": {
"required": [
"scored"
],
"properties": {
"type": {
"const": "arts"
},
"scored": {
"type": "number"
},
"remarks": {
"type": "string"
}
}
}
}
}
和我的 JSON
{
"exam": [
{
"type": "science",
"rule": {
"sciencePattern": {
"marks": {
"scored": [10]
}
}
}
},
{
"type": "arts",
"scored": 10 //This should complain as 'scored' is available above in science
}
]
}
【问题讨论】:
-
在这里,我更新了“EDIT 1”部分下的架构。但是,如果我在“艺术”对象中添加“得分”属性,它仍然会抱怨。有什么指点吗?
-
最后,我做到了,架构验证按预期工作。请参阅以下部分。谢谢。
标签: json jsonschema json-schema-validator