父/子层次结构和jsonschema

问题描述 投票:1回答:1

我正在尝试提出一个json模式来验证这种文档:

 {
  "rootData": {
    "parent1": [
      {
        "parent1": [
          {
            "leaf1": {
              "attr": "value"
            }
          }
        ]
      },
      {
        "parent2": [
          {
            "leaf1": {
              "attr": "value"
            }
          }
        ]
      },
      {
        "leaf1": {
          "attr": "value"
        }
      }
    ]
  },
  "rootInfo": {
    "i1": 1
  }
 }

一些信息:

  1. “ rootData”只能包含一个父对象,parent1或parent2
  2. parent1 / parent2可以在层次结构中的任何位置切换为parent2 / parent1
  3. 没有深度限制:只要一个父级包含另一个父级,我们就可以做得越来越深。

我想我能够弄清楚如何表示嵌入式父/子部件的层次结构性质。但是我不知道如何定义“ rootData”顶层,更确切地说是在“ parent1”或“ parent2”之间进行选择,因为我不能使用oneOf(我认为...)

    {
  "$schema": "http://json-schema.org/draft-06/schema#",
  "definitions": {
    "parent1": {
      "$id": "#parent1",
      "type": "object",
      "properties": {
        "parent1": {
          "$ref": "#node"
        }
      }
    },
    "parent2": {
      "$id": "#parent2",
      "type": "object",
      "properties": {
        "parent2": {
          "$ref": "#node"
        }
      }
    },
    "leaf1": {
      "$id": "#leaf1",
      "type": "object",
      "properties": {
        "leaf1": {
          "type": "object",
          "properties": {
            "attr": {
              "type": "string"
            }
          },
          "required": [
            "attr"
          ]
        }
      }
    },
    "node": {
      "$id": "#node",
      "type": "array",
      "items": {
        "oneOf": [
          {
            "$ref": "#parent1"
          },
          {
            "$ref": "#parent2"
          },
          {
            "$ref": "#leaf1"
          }
        ]
      }
    }
  },
  "type": "object",
  "properties": {
    "rootData": {
      "properties": {
        //I tried several things here minProperties/maxProperties or oneOf ... but I actually don't know how to reuse my previous parent1 or parent2 definitions ...
        }
    }
  }
}

欢迎任何帮助!

Thx

json schema parent-child hierarchy jsonschema
1个回答
0
投票

"required":["parent1"]"required":["parent2"]约束添加到parent1和parent2定义,并使用oneOf

{
    "$schema": "http://json-schema.org/draft-06/schema#",
    "definitions": {
        "parent1": {
            "$id": "#parent1",
            "type": "object",
            "required": ["parent1"],
            "properties": {
                "parent1": {"$ref": "#node"}
            }
        },
        // ...
    },
    "type": "object",
    "properties": {
        "rootData": {
            "oneOf": [
                {"$ref": "#parent1"},
                {"$ref": "#parent2"}
            ]
        }
    }
}

[如果您尝试使用anyOf并成功了,那是因为您的parent1parent2定义相互验证:parent1针对parent2对象进行了验证,因为它忽略了“ parent2”属性,并且没有“ parent1”属性时有效;反之亦然,对于“ parent1”。

© www.soinside.com 2019 - 2024. All rights reserved.