【问题标题】:How to switch-case on fields within JSON Schema?如何在 JSON Schema 中的字段上切换大小写?
【发布时间】:2018-10-22 16:43:18
【问题描述】:

我正在使用 Python 的 jsonschema 来验证 JSON 记录。这是一个示例架构。这里只有两个案例,但想象一个类似的场景,它有一百个这样的案例。

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "oneOf": [
      {
        "type": "object",
        "required": ["a", "b", "c"],
        "properties": {
          "a": {"type": "integer", "enum": [0]},
          "b": {"type": "integer", "enum": [0, 2, 4, 6, 8]},
          "c": {"type": "string", "enum": ["always the same"]}
        }
      },
      {
        "type": "object",
        "required": ["a", "b", "c"],
        "properties": {
          "a": {"type": "integer", "enum": [1]},
          "b": {"type": "integer", "enum": [1, 3, 5, 7, 9]},
          "c": {"type": "string", "enum": ["always the same"]}
        }
      }
    ]
}

关键问题是"c" 字段的重复。我希望能够在"a" 上切换大小写,验证相应的"b",但"c" 始终保持不变。我不想把"c" 拼出一百次。这可以吗?

谢谢!

【问题讨论】:

    标签: jsonschema python-jsonschema


    【解决方案1】:

    是的,可以做到。实际上,最好只输入 anyOf/oneOf 更改的部分。

    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "properties": {
        "c": { "const": "always the same" }
      },
      "required": ["a", "b", "c"],
      "anyOf": [
        {
          "properties": {
            "a": { "const": 0 },
            "b": { "enum": [0, 2, 4, 6, 8] }
          }
        },
        {
          "properties": {
            "a": { "const": 1 },
            "b": { "enum": [1, 3, 5, 7, 9] }
          }
        }
      ]
    }
    

    【讨论】:

    • 使用draft-7,您还可以使用const,而不是使用单个值的枚举。
    • 啊,是的,我清理了一些东西,但我错过了那个。 const 已添加到 draft-06 中,供任何需要知道的人使用。
    猜你喜欢
    • 2022-01-25
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-24
    • 2016-06-09
    • 1970-01-01
    相关资源
    最近更新 更多