我很难用json模式来编写验证规则。以下是我的json格式的数据:
{
"headers" : {
"api_key" : "aaa-bbb-ccc-ddd-eee"
},
"query_string" : {
"apikey" : "aaa-bbb-ccc-ddd-eee"
}
}我需要一条规定:
至少“headers>api_key”或“query_string-> least”需要出现在json中,而不是两者都存在。
到目前为止,下面是我的模式验证:
{
"title": "Application Get Single",
"type": "object",
"properties": {
"headers": {
"type": "object",
"properties": {
"api_key": {
"type": "string"
}
}
},
"query_string": {
"type": "object",
"properties": {
"apikey": {
"type": "string"
}
}
}
},
"anyOf": [
{"required": ["headers"["api_key"]]}, // what should this be??
{"required": ["query_string"["apikey"]]} // what should this be??
]
}我认为这是我正在寻找的anyOf,但我不知道如何引用上面嵌套的json项。
现在我收到了一个错误:
JSON语法格式错误
我使用的是贾斯汀·彩虹,因为我正在使用PHP。
发布于 2017-11-16 22:12:06
有几种方法。最直接的办法是:
{
"title": "Application Get Single",
"type": "object",
"properties": {
"headers": {
"type": "object",
"properties": {
"api_key": {
"type": "string"
}
}
},
"query_string": {
"type": "object",
"properties": {
"apikey": {
"type": "string"
}
}
}
},
"anyOf": [
{
"properties": {
"headers": {
"type": "object",
"required":["api_key"]
}
}
},
{
"properties": {
"query_string": {
"type": "object",
"required":["apikey"]
}
}
}
]
}您可能还需要根对象上的"minProperties": 1,以确保标头或query_string的存在。
编辑:只需重新阅读问题,如果headers.api_key和query_string.apikey是相互排斥的,则anyOf改为oneOf。
发布于 2017-11-23 20:02:13
诀窍是“而不是另一方”。下面是我的建议(假设草案-06或更高版本,请参见下面的草案-04):
{
"title": "Application Get Single",
"type": "object",
"properties": {
"headers": {
"type": "object",
"properties": {
"api_key": {
"type": "string"
}
}
},
"query_string": {
"type": "object",
"properties": {
"apikey": {
"type": "string"
}
}
}
},
"oneOf": [
{
"required": ["headers"],
"query_string": false
},
{
"required": ["query_string"],
"headers": false
}
]
}对于草案-04,将false替换为{"not": {}},这意味着同样的事情,但读起来很烦人。但是您不能在草案04中的大多数地方使用布尔模式,所以您需要用冗长的方式说“这个属性一定不存在”。
https://stackoverflow.com/questions/47336315
复制相似问题