4

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.

shadowtalker
  • 12,529
  • 3
  • 53
  • 96

1 Answers1

6

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 ...
    ]
  }
}
Jason Desrosiers
  • 22,479
  • 5
  • 47
  • 53
  • 2
    To see the alternatives I mentioned, see https://stackoverflow.com/questions/38717933/jsonschema-attribute-conditionally-required/38781027#38781027, especially the "Implication" method. – Jason Desrosiers Aug 29 '18 at 03:52