首页 > 解决方案 > JSON Schema if/then 需要嵌套对象

问题描述

我有一个 JSON:

{
    "i0": {
        "j0": {
            "a0": true
        }
    },
    "i1": {
        "j1": {
            "a1": "stuff"
        }
    }
}

我想要一个验证:如果a0是真的,a1应该是必需的。

我的架构目前是:

{
    "$schema": "http://json-schema.org/draft-07/schema",
    "id": "id",
    "type": "object",
    "required": [
        "i0",
        "i1"
    ],
    "allOf": [
        {
            "if": {
                "properties": {
                    "i0": {
                        "j0": {
                            "a0": true
                        }
                    }
                }
            },
            "then": {
                "properties": {
                    "i1": {
                        "j1": {
                            "required": [
                                "a1"
                            ]
                        }
                    }
                }
            }
        }
    ]
}

这个条件似乎实际上并没有运行。required或者,如果我尝试将其置于与我正在检查的值相同的水平上,我已经看到了一个非常相似的工作条件。如:

"allOf": [
    {
        "if": {
            "a0": true
        },
        "then": {
            "required": [
                "a1"
            ]
        }
    }
]

但这a1需要j0a1. 如何根据 underj1的值要求对象 under j0

标签: jsonjsonschemajson-schema-validator

解决方案


尝试这个:

{
  "if":{
    "type":"object",
    "properties":{
      "i0":{
        "type":"object",
        "properties":{
          "j0":{
            "type":"object",
            "required":["a0"]
          }
        },
        "required":["j0"]
      }
    },
    "required":["i0"]
  },
  "then":{
    "type":"object",
    "properties":{
      "i1":{
        "type":"object",
        "properties":{
          "j1":{
            "type":"object",
            "required":["a1"]
          }
        },
        "required":["j1"]
      }
    },
    "required":["i1"]
  }
}

您必须使用if/then关键字中的整体结构,从它们具有的任何共同根开始。i0在这种情况下,它们的路径在/属性处开始发散i1,因此您必须从该点包含整个结构。

type关键字确保您拥有一个对象,否则当使用其他类型(如 s 或 s)时,架构可能会通过string验证boolean

required关键字确保if/then子模式仅分别匹配实际包含i0.j0.a0/i1.j1.a1属性路径的对象。

此外,/`a1 属性的required关键字a0仅指定它们存在。如果需要,您可以向该子模式添加更多验证。


推荐阅读