首页 > 解决方案 > Json Schema Validation - 引用子模式

问题描述

我正在尝试针对具有以下结构的模式验证 json 数据:

{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://foo.bar/my.schema.json",
  "$def": {
    "parentType": {
      "type": "object",
      "properties": {
        "child": {
          "$ref": "#/$def/childType"
        }
      },
      "required": [
        "child"
      ]
    },
    "childType": {
      "type": "object",
      "properties": {
        "name": {
          "type": "string"
        }
      },
      "required": [
        "name"
      ]
    }
  },
  "type": "object",
  "properties": {
    "parent": {
      "$ref": "#/$def/parentType"
    }
  },
  "required": [
    "parent"
  ]
}

以下是json数据:

{
  "parent": {
    "child": {
      "name": "aaa",
    }  
  }
}

如何通过 json 模式验证确保以下字段/parent/child/name的值是aaabbb

我不想对 childType 定义添加限制,因为我想保留 childType“通用”的类型定义,并稍后在$def块之外添加限制。这样,我可以将相同的 childType 用于不同的场景,其中name可能不是“aaa”或“bbb”。

谢谢!

标签: jsonschemajsonschema

解决方案


当您使用 draft2019-09时,您可以$ref与其他关键字一起使用。这在早期的草稿中是不允许的,例如draft-07.

例如,与其拥有...

"properties": {
    "parent": {
      "$ref": "#/$def/parentType"
    }
  },

你可以有...

  "properties": {
    "parent": {
      "$ref": "#/$def/parentType",
      "enum": ["aaa", "bbb"]
    }
  }

如果要使用多个引用,则需要将它们作为包装在allOf.


推荐阅读