【问题标题】:Is there a way to use JSON schemas to enforce values between fields?有没有办法使用 JSON 模式来强制字段之间的值?
【发布时间】:2016-03-16 20:01:55
【问题描述】:

我最近开始使用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,反之亦然。 p>

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


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

【问题讨论】:

  • 试试"^-1|[\\d]+$" 换成pattern。组在这里没有意义,您不想匹配-11。
  • 哦,是的,谢谢@flaschbier。

标签: python json jsonschema


【解决方案1】:

您可以通过将以下内容添加到您的 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+$"
            }
        }
    }

【讨论】:

  • 是的...整数作为字符串不会是我的首选。谢谢你的建议。我试试看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 2022-12-17
  • 2020-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多