JSON Schema dependencies: enum content depends on

2019-07-26 00:59发布

I have an enum with a first set of choices, and a second enum whose content depends on the choice made in the first enum.

Here's a simple example of what I have at present (not right):

"fontGroup": {
    "title": "Font Group",
    "type": "string",
    "enum": [
        "Roboto",
        "Noto",
        "Alegreya"
    ],
    "default": "Roboto"
},
"fontFamily": {
    "title": "Font Family",
    "type": "string",
    "enum": [
        "Roboto Slab",
        "Roboto Condensed",
        "---",
        "Noto Sans",
        "Noto Serif",
        "---",
        "Alegreya SC",
        "Alegreya Sans"
    ],
    "default": "Roboto Slab"
}

Of course, if Noto is selected from the first enum then only the Noto related choices in the second enum are valid. It is invalid to select Noto in combination with Roboto Condensed, for example.

How can this be specified in the schema?

1条回答
再贱就再见
2楼-- · 2019-07-26 01:44

You can not refer to a relative property as of draft-07 and below, but you can enumerate all possible object variations:

{
  "type": "object",
  "oneOf": [
    {
      "properties": {
        "fontGroup": {
          "const": "Roboto"
        },
        "fontFamily": {
          "enum": [
            "Roboto Slab",
            "Roboto Condenced"
          ]
        }
      }
    },
    {
      "properties": {
        "fontGroup": {
          "const": "Noto"
        },
        "fontFamily": {
          "enum": [
            "Noto Sans",
            "Noto Serif"
          ]
        }
      }
    },
    {
      "properties": {
        "fontGroup": {
          "const": "Alegreya"
        },
        "fontFamily": {
          "enum": [
            "Alegreya SC",
            "Alegreya Sans"
          ]
        }
      }
    }
  ]
}

const keyword is not available in draft-04, you can change it to single-value enum: "enum":["Roboto"].

查看更多
登录 后发表回答