【问题标题】:Python jsonschema, allowing nothing, or require one and only one of two fieldsPython jsonschema,什么都不允许,或者只需要两个字段之一
【发布时间】:2019-11-07 17:01:10
【问题描述】:

我正在使用适用于 Python 的 jsonschema,并且我正在尝试允许以下任何一项:

{}
# or
{
    'id': 'd6a4def3-4a6a-4fb4-a38e-f98ea48f708a'
}
# or
{
    'status': 'Done'
}

但我不想允许以下内容,因为提供了两个字段:

{
    'id': 'd6a4def3-4a6a-4fb4-a38e-f98ea48f708a',
    'status': 'Done'
}

这是我目前所拥有的,它允许按照我的意愿提供一个或另一个字段,但它不允许任何内容。

GET_CALL = {
    "type": "object",
    "additionalProperties": False,
    "properties": {
        "id": {
            "type": "string",
            "pattern": REGEX_EXPRESSIONS['UUID4'], # Matches a UUID4 format
        },
        "status": {
            "type": "string",
            "enum": ["Done", "Ready"],
        },
    },
    "oneOf": [ # This makes it so I can only have one or the other but it doesn't allow nothing.
        {"required": ["id"]},
        {"required": ["status"]}
    ],
}

【问题讨论】:

    标签: python python-3.x jsonschema


    【解决方案1】:

    您需要您的oneOf 来涵盖所有情况。幸运的是,这并不太复杂。

    这是您指定的内容所需的架构。您可以将其应用到现有架构中。

    {
      "oneOf": [
        {
          "additionalProperties": false
        },
        {
          "required": [
            "id"
          ]
        },
        {
          "required": [
            "status"
          ]
        }
      ]
    }
    

    (草案 7 JSON 架构)

    您可以在jsonschema.dev 进行测试(链接已预加载此架构和测试实例)

    为了澄清,你仍然需要type: object

    【讨论】:

    • 欢迎您!如果您有不属于这里的问题,请随时加入 JSON Schema slack。我们还从这里监控 jsonschema 标签 =]
    • 获得了 slack 的链接?
    • json-schema.org 上讨论链接 - 我们真的需要让它更明显! 添加到长长的待办事项列表中
    猜你喜欢
    • 2018-11-29
    • 2020-07-29
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2021-08-12
    • 2014-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多