JSON Schema - 如何引用枚举值并将多组枚举组合到一个属性中?

时间:2017-12-28 09:49:18

标签: jsonschema

我在架构中有两个枚举字段:

{ ...
  "prop1": {
    oneOf": [{
      "enum": [
        "VAL1",
        "VAL2"],
      "type": "string"
      },{
        "type": "null"}]
  },
  "prop2": {
    oneOf": [{
      "enum": [
        "VAL3",
        "VAL4"],
      "type": "string"
      },{
        "type": "null"}]
}

我想创建第三个枚举字段prop3,并允许来自prop1prop2的值。 我可以复制值:

{ ...
  "prop3": {
    oneOf": [{
      "enum": [
        "VAL1",
        "VAL2"
        "VAL3",
        "VAL4"
        ],
      "type": "string"
      },{
        "type": "null"}]
  }
}

但是,当我将prop3prop1添加到prop2时,我希望definition自动获取新值。

我可以为枚举值创建pc,然后在两个地方使用它吗? 我怎样才能加入两组这样的枚举?

1 个答案:

答案 0 :(得分:1)

您可以使用anyOf关键字有效地组合枚举。

{
  "type": "object",
  "properties": {
    "prop1": { "$ref": "#/definitions/prop1" },
    "prop2": { "$ref": "#/definitions/prop2" },
    "prop3": { "$ref": "#/definitions/prop3" }
  },
  "definitions": {
    "prop1": { "enum": ["VAL1", "VAL2"] },
    "prop2": { "enum": ["VAL3", "VAL4"] },
    "prop3": {
      "anyOf": [
        { "$ref": "#/definitions/prop1" },
        { "$ref": "#/definitions/prop2" }
      ]
    }
  }
}