JSON Schema条件:基于另一个字段的值需要字段

Art*_*nos 7 json jsonschema

我正在尝试实现这个条件:根据另一个字段的值需要字段,即如果请求带有"index":"true",则需要"id"元素:true.

这是一个示例模式:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "test title",
  "type": "object",
  "properties": {
    "data": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/Item"
      },
      "minItems": 0
    }
  },
  "required": [
    "data"
  ],
  "definitions": {
    "Item": {
      "type": "object",
      "properties": {
        "id": {
          "type": [
            "integer",
            "string"
          ]
        },
        "type": {
          "type": "string"
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如何实施?

任何指针都会有所帮助.

Tal*_*box 8

你的样品chema对我来说很奇怪,但是对于票证说明中的验证案例你可以使用json shema的这一部分:

"properties": {
    "data": {
        "oneOf": [
            {
                "type": "object",
                "required": [
                    "index"
                ],
                "properties": {
                    "index": {
                        "type": "boolean",
                        "enum": [false]
                    }
                }
            },
            {
                "type": "object",
                "required": [
                    "index",
                    "id"
                ],
                "properties": {
                    "index": {
                        "type": "boolean",
                        "enum": [true]
                    },
                    "id": {
                        "type": "boolean"
                    }
                }
            }
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你想验证一个参数,当其他参数等于某个值时,这个技巧对你有帮助.