JSON Schema: 验证确切存在一个属性
我想要验证一个JSON结构,其中必须存在userId
键或appUserId
键(只能有一个,不能同时存在)。
比如,
{ "userId": "X" }
{ "appUserId": "Y" }
是有效的,但是:
{ "userId": "X", "appUserId": "Y"}
{ }
则无效。
我该如何使用JSON Schema来验证这个条件呢?我试过oneOf
这个关键词,但它是针对值的,不是针对键的。
2 个回答
0
我会在方案中结合使用最小/最大属性和额外属性:
{
"type" : "object",
"properties" : {
"userId": { "type": "string" },
"appUserId": { "type": "string" },
},
"maxProperties": 1,
"minProperties": 1,
"additionalProperties": false
}
// invalid cases
{ }
{ "userId": "111", "appUserId": "222" }
{ "anotherUserId": "333" }
// valid cases
{ "userId": "111" }
{ "appUserId": "222" }
5
这个对我有效:
from jsonschema import validate
schema = {
"type" : "object",
"properties" : {
"userId": {"type" : "number"},
"appUserId": {"type" : "number"},
},
"oneOf": [
{
"type": "object",
"required": ["userId"],
},
{
"type": "object",
"required": ["appUserId"],
}
],
}
validate({'userId': 1}, schema) # Ok
validate({'appUserId': 1}, schema) # Ok
validate({'userId': 1, 'appUserId': 1}, schema) # ValidationError