jsonschema枚举值取决于另一个枚举值

时间:2018-08-22 17:33:30

标签: jsonschema

我有一张适用于我的应用程序的可接受的输入组合表:

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

不接受其他值组合。

如何在JSON模式中对其进行编码? “模式的其余部分”看起来像这样:

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

当前,我的应用程序使用的是Draft 4,因为jsonschema package的最新稳定版本支持该草案。

1 个答案:

答案 0 :(得分:1)

鉴于选项的数量是固定的,我认为最好的办法是列举所有选项。与替代方案相比,该方案将更易于阅读和维护。

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