2

我正在使用 Pythonjsonschema来验证 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"字段的重复。我希望能够 switch-case on "a",验证相应的"b",但"c"始终保持不变。我不想拼出"c"一百个不同的时间。这可能吗?

谢谢!

4

1 回答 1

4

是的,这是可以做到的。事实上,最好只放入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] }
      }
    }
  ]
}
于 2018-10-23T02:38:01.633 回答