shadowtalker
shadowtalker

Reputation: 13903

jsonschema enum values conditional on another enum value

I have a table of acceptable input combinations for my application:

noises   appearance
------   ----------
squeaks  fluffy
purrs    fluffy
hisses   fluffy
peeps    feathers
chirps   feathers
squeaks  feathers
hisses   scaly

No other combination of values is acceptable.

How can this be encoded in JSON Schema? The "rest of the schema" would look kind of like this:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "array",
  "items": {
    "type": "object",
    "required": ["noise", "appearance"]
    "properties": {
      "noise": ...,
      "appearance": ...
    }
  }

Currently my application is using Draft 4 because it's what's supported by the last stable version of the jsonschema package.

Upvotes: 5

Views: 5001

Answers (1)

Jason Desrosiers
Jason Desrosiers

Reputation: 24489

Given that there are a small and fixed number of options, I think the best thing is to enumerate all the options. The schema will be easier to read and maintain than the alternatives.

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "array",
  "items": {
    "type": "object",
    "required": ["noise", "appearance"],
    "properties": {
      ... any common properties ...
    },
    "anyOf": [
      {
        "properties": {
          "noise": { "enum": ["squeaks"] },
          "appearance": { "enum": ["fluffy"] }
        }
      },
      {
        "properties": {
          "noise": { "enum": ["purrs"] },
          "appearance": { "enum": ["fluffy"] }
        }
      },
      ... other combinations ...
    ]
  }
}

Upvotes: 8

Related Questions