【问题标题】:How to write JSON Schema for property depend on other filed's value?如何为属性编写 JSON Schema 取决于其他字段的值?
【发布时间】:2016-11-07 08:41:35
【问题描述】:

这是我的要求:当 num==0 时,需要 a;当 num==1 时,需要 b。

{
  "type": "object",
  "properties": {
    "num": { "type": "integer" },
    "a": { "type": "string" },
    "b": { "type": "string" }
  }
  "required": [ "num" ]
}

【问题讨论】:

  • 我还没有找到值依赖的解决方案。

标签: jsonschema


【解决方案1】:

我目前的解决方案:

{
  "type": "object",
  "oneOf": [
    {"$ref": "#/definitions/0"},
    {"$ref": "#/definitions/1"},
  ],
  "definitions": {
    "0": {
      "properties": {
        "num": {"enum": [0]},
        "a": {"type": "string"}
      },
      "required": ["num", "a"]
    },
    "1": {
      "properties": {
        "num": {"enum": [1]},
        "b": {"type": "string"}
      },
      "required": ["num", "b"]
    }
  } 
}

我正在使用jsonschema,它返回is not exactly on from <#definitions/0>。那不是我想要的。我希望它可以返回有关详细信息的消息,例如a 是必需的。

【讨论】:

    【解决方案2】:

    改进版:

    {
      "type": "object",
      "properties": {
        "num": { "type": "integer" },
        "a": { "type": "string" },
        "b": { "type": "string" }
      }
      "required": [ "num" ],
      "dependencies": {
        "a": {
          "properties": {
            "num": {
              "enum": [0]
            }
          }
        },
        "b": {
          "properties": {
            "num": {
              "enum": [1]
            }
          }
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-11
      • 1970-01-01
      • 2018-01-27
      • 2021-07-08
      • 2016-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多