我必须使用 json-schema 验证 json。
验证规则:(仅适用于 prop1、prop2、prop3)
这里,valid 是指任何字符串,但不仅仅是空格;无效意味着只有空格
使用下面的 json 模式,我能够实现除最后一个验证规则之外的所有内容。
json
[{
"prop1": "Property1",
"prop2": "Property2",
"prop3": "Property3",
"prop4": "Property4"
},
{
"prop1": " ",
"prop2": "Property2",
"prop3": "Property3",
"prop4": "Property4"
},
{
"prop1": " ",
"prop2": "",
"prop3": "Property3",
"prop4": "Property4"
},
{
"prop1": " ",
"prop2": " ",
"prop3": " ",
"prop4": "Property4"
},
{
"prop1": "Property1",
"prop4": "Property4"
},
{
"prop1": " ",
"prop4": "Property4"
},
{
"prop2": "Property2",
"prop3": "Property3",
"prop4": "Property4"
},
{
"prop2": " ",
"prop3": " ",
"prop4": "Property4"
},
{
"prop2": " ",
"prop3": "Property3",
"prop4": "Property4"
},
{
"prop4": "Property4"
}
]
json 架构
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "array",
"items": {
"type": "object",
"properties": {
"prop1": {
"type": "string"
},
"prop2": {
"type": "string"
},
"prop3": {
"type": "string"
},
"prop4": {
"type": "string"
}
},
"required": [
"prop4"
],
"if": {
"oneOf": [{
"allOf": [{
"properties": {
"prop1": {
"pattern": "^(?! +$).*"
}
}
},
{
"properties": {
"prop2": {
"pattern": "^(?! +$).*"
}
}
},
{
"properties": {
"prop3": {
"pattern": "^(?! +$).*"
}
}
}
]
},
{
"allOf": [{
"properties": {
"prop1": {
"pattern": "^[ ]+$"
}
}
},
{
"properties": {
"prop2": {
"pattern": "^[ ]+$"
}
}
},
{
"properties": {
"prop3": {
"pattern": "^[ ]+$"
}
}
}
]
}
]
},
"then": {
"required": ["prop1", "prop2", "prop3"]
},
"else" : {
"allOf" : [
{"not" : { "required" : ["prop1"] } },
{"not" : { "required" : ["prop2"] } },
{"not" : { "required" : ["prop3"] } }
]
}
}
}
根据此模式,json 数组传递索引 0,3,9;索引 1、2、4、5、6、7、8 失败。 但我还需要索引 5 才能通过(根据最后的验证规则)。 我找到了如何检查 json 模式中是否存在属性,但没有找到任何用于检查属性是否不存在的内容。
请建议更改 json 模式以实现最后的验证规则。
您的要求有点模糊和混乱......
这是我对它们的解释。
应用以下约束:
#pattern
- [^\\s] // negated set of whitespace characters
- . // matches any character except line breaks
- * // 0 or more of the preceding token
prop1
、prop2
、prop3
是可选(非必需)属性prop1
、prop2
、prop3
均不存在prop1
、prop2
、prop3
的任何组合均不存在任何值,例如""
或仅空格 " "
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "array",
"items": {
"type": "object",
"properties": {
"prop1": {
"type": "string",
"pattern": "[^\\s].*"
},
"prop2": {
"type": "string",
"pattern": "[^\\s].*"
},
"prop3": {
"type": "string",
"pattern": "[^\\s].*"
},
"prop4": {
"type": "string"
}
},
"required": [
"prop4"
]
}
}