簡體   English   中英

父/子層次結構和 jsonschema

[英]parent/child hierarchy & jsonschema

我正在嘗試提出一個 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 ...
        }
    }
  }
}

歡迎任何幫助!

謝謝

"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”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM