Search code examples
validationswitch-statementjsonschemapython-jsonschema

How to emulate a switch statement (switch-case) in a JSON Schema?


I'm using a JSON Schemajsonschema to validate JSON records. Here's an example schema. It has only two cases here, but imagine a similar scenario where it instead has a hundred cases laid out like these.

{
    "$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"]}
        }
      }
    ]
}

The key issue is the duplication of the "c" field. I'd like to be able to switch-case on "a", validating for a corresponding "b", but having "c" always remain the same. I don't want to have to spell out "c" a hundred different times. Is this possible to do?

Thanks!


Solution

  • Yes, it can be done. In fact, it's good practice to only put in anyOf/oneOf the parts that change.

    {
      "$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] }
          }
        }
      ]
    }