Skip to main content
 首页 » 编程设计

python之有没有办法使用 JSON 模式在字段之间强制执行值

2025年04月02日19rubylouvre

我最近开始玩 JSON schemas开始执行 API 负载。我在为遗留 API 定义架构时遇到了一些障碍,该 API 具有一些非常笨拙的设计逻辑,导致(以及糟糕的文档)客户滥用端点。

这是目前的架构:

{ 
    "type": "array", 
    "items": { 
        "type": "object", 
        "properties": { 
            "type": { 
                "type": "string" 
            }, 
            "object_id": { 
                "type": "string" 
            }, 
            "question_id": { 
                "type": "string", 
                "pattern": "^-1|\\d+$" 
            }, 
            "question_set_id": { 
                "type": "string", 
                "pattern": "^-1|\\d+$" 
            }, 
            "timestamp": { 
                "type": "string", 
                "format": "date-time" 
            }, 
            "values": { 
                "type": "array", 
                "items": { 
                    "type": "string" 
                } 
            } 
        }, 
        "required": [ 
            "type", 
            "object_id", 
            "question_id", 
            "question_set_id", 
            "timestamp", 
            "values" 
        ], 
        "additionalProperties": false 
    } 
} 

请注意,对于 question_id 和 question_set_id,它们都采用可以是 -1 或其他非负整数的数字字符串。

我的问题:如果 question_id 设置为 -1,是否有办法强制将 question_set_id 也设置为 -1,反之亦然。

如果我可以让解析器验证它而不是必须在应用程序逻辑中进行检查,那就太棒了。


只是为了额外的上下文,我一直在使用 python 的 jsl 模块来生成这个模式。

请您参考如下方法:

您可以通过将以下内容添加到您的 items 架构来实现所需的行为。它断言模式必须至少符合列表中的模式之一。要么都是“-1”,要么都是正整数。 (我假设您有充分的理由将整数表示为字符串。)

"anyOf": [ 
    { 
        "properties": { 
            "question_id": { "enum": ["-1"] }, 
            "question_set_id": { "enum": ["-1"] } 
        } 
    }, 
    { 
        "properties": { 
            "question_id": { 
                "type": "string", 
                "pattern": "^\\d+$" 
            }, 
            "question_set_id": { 
                "type": "string", 
                "pattern": "^\\d+$" 
            } 
        } 
    }