如何编写json模式来强制其他属性的条件存在?

时间:2017-01-25 09:07:09

标签: json jsonschema json-schema-validator

Schema应验证以下json对象,不应允许任何其他属性。

{
  "id": "11111111111111111111111111111111",
  "status": "employed",
  "company_name": "Google"
}

{
  "id": "00000000000000000000000000000000",
  "status": "unemployed"
}

架构草案第4版:

{
  "type": "object",
  "additionalProperties":false,
  "required": [
    "status",
    "id"
  ],
  "properties": {
    "id": {
      "type": "string"
    },
    "status": {
      "type": "string",
      "enum":["unemployed", "employed"]
    },
    "company_name": {
      "type": "string"
    }
  },
  "dependencies": {
    "company_name": {
      "properties": {
        "status": {
          "enum": [
            "employed"
          ]
        }
      }
    }
  }
}

此架构看起来正确,但它不会使跟随json对象失效。

{
  "id": "00000000000000000000000000000001",
  "status": "employed"
}

它应该是无效的,因为“状态”是“已使用”但未提供所需的属性“company_name”。

1 个答案:

答案 0 :(得分:1)

可以使用anyOf进行此操作,但不确定如何使用dependencies进行操作。

{
  "type": "object",
  "additionalProperties": false,
  "required": [
    "status",
    "id"
  ],
  "properties": {
    "id": {
      "type": "string"
    },
    "status": {
      "type": "string",
      "enum": [
        "unemployed",
        "employed"
      ]
    },
    "company_name": {
      "type": "string"
    }
  },
  "anyOf": [
    {
      "properties": {
        "status": {
          "enum": [
            "employed"
          ]
        }
      },
      "required": [
        "company_name"
      ]
    },
    {
      "properties": {
        "status": {
          "enum": [
            "unemployed"
          ]
        }
      },
      "not": {
        "required": [
          "company_name"
        ]
      }
    }
  ]
}

感谢@esp