首页 > 解决方案 > 在 IF 条件中引用内部属性 - JSON Schema

问题描述

以下是描述问题的示例架构

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "definitions": {
        "person": {
            "type": "object",
            "properties": {
                "age": {
                    "type": "string"
                }
            }
        }
    },
    "properties": {
        "child": {
            "$ref": "#/definitions/person"
        }
    },
    "required": [
        "child"
    ],
    "if": {
        "properties": {
            "person/age": {
                "const": "3"
            }
        }
    },
    "then": {
        "properties": {
            "guardian": {
                "$ref": "#/definitions/person"
            }
        },
        "required": [
            "guardian"
        ]
    }
}

有没有办法在 person 对象中引用年龄?

{"child":{"age":"3"}}. 由于缺少监护人标签,应该会失败

由于缺少监护人对象,上述数据应该会失败。

标签: jsonschemajson-schema-validator

解决方案


请记住,这if只是针对实例验证的常规模式。就像嵌套properties任何嵌套对象结构一样。

{
  "type": "object",
  "properties": {
    "child": {
      "type": "object",
      "properties": {
        "age": { "const": "3" }
      },
      "required": ["age"]
    }
  },
  "required": ["child"]
}

请注意,typeandrequired关键字对于不会无意中触发then架构是必要的。例如,如果没有它们,这些将导致then在您可能不希望触发时触发。

{}
{ "child": null }
{ "child": {} }

推荐阅读