JSON Schema: 验证确切存在一个属性

6 投票
2 回答
2754 浏览
提问于 2025-04-20 15:19

我想要验证一个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

撰写回答