How to implement conditional nested properties with JSON Schema

Viewed 450

I have base json schema base.schema.json

{
  "$id": "base.schema.json",
  "type": "object",
  "properties": {
    "remote_os": {
      "default": "Windows",
      "enum": [
        "Linux",
        "Windows" ]
     }
  },
  "required": ["remote_os"]
}

Now referenced the schema definition in another json

{
  "$id": "update.schema.json",
  "properties": {
    "common_data": {
      "$ref": "base.schema.json"
    }
  },
  "allOf": [
    {
      "if": {
        "properties": {
          "common_data": {
            "remote_os": {
              "const": "Windows"
            }
          }
        }
      },
      "then": {
        "properties": {
          "file": {
            "pattern": "^(.*.)(exe)$"
          }
        }
      }
    },
    {
      "if": {
        "properties": {
          "common_data": {
            "remote_os": {
              "const": "Linux",
              "required": [
                "remote_os"
              ]
            }
          }
        }
      },
      "then": {
        "properties": {
          "file": {
            "pattern": "^(.*.)(bin)$"
          }
        }
      }
    }
  ]
}

Basically adding the if-else logic to make sure for remote_os=Linux file should ended up with .bin and remote_os=Windows file should ended up with .exe
Now I am trying to validate against below data

{
  "common_data": {
    "remote_os": "Linux"
  },
  "file": "abc.bin"
}

[<ValidationError: "'abc.bin' does not match '^(.*.)(exe)$'">]. Not sure what's wrong here

1 Answers

I think you are over complicating it - surly just if/then/else?

{
  "if": {
    "properties": { "common_data": "properties": { "remote_os": { "const": "Windows" } } }
  },
  "then": {
    "properties": { "file": { "pattern": "^(.*.)(exe)$" } }
  },
  "else": {
    "properties": { "file": { "pattern": "^(.*.)(bin)$" } }
  }
}
Related