使用JSON Schema验证另一个属性

时间:2015-07-05 21:09:27

标签: json jsonschema json-schema-validator

在下面的模型中," category_id"只有在"详细信息和#34;数组是空的。

如果"详细信息"数组不为空," category_id"不需要财产。

如何使用JSON Schema执行此操作?

{
    "description": "Expense model validation.",
    "type": "object",
    "properties": {
        "description": {
            "type": "string"
        },
        "category_id": {
            "type": "string"
        },
        "detail": {
            "type": "array",
            "items": {
                "description": "Expense detail",
                "type": "object",
                "properties": {
                    "description": {
                        "type": "string"
                    }
                },
                "required": [ "description" ]
            }
        }
    },
    "required": [ "description", "category_id" ]
}

1 个答案:

答案 0 :(得分:1)

您可以使用anyOf检查category_id是否存在,或detail是否存在且至少有一项。

{
  "description": "Expense model validation.",
  "type": "object",
  "properties": {
    "description": { "type": "string" },
    "category_id": { "type": "string" },
    "detail": {
      "type": "array",
      "items": {
        "description": "Expense detail",
        "type": "object",
        "properties": {
          "description": { "type": "string" }
        },
        "required": ["description"]
      }
    }
  },
  "required": ["description"],
  "anyOf": [
    { "required": ["category_id"] },
    {
      "properties": {
        "detail": { "minItems": 1 }
      },
      "required": ["detail"]
    }
  ]
}