【问题标题】:Is it possible to reference to JSON data itself within a schema definition?是否可以在模式定义中引用 JSON 数据本身?
【发布时间】:2021-12-19 10:07:51
【问题描述】:

是否可以定义 JSON 模式来检查内部数据完整性?这样"ba" 之类的错误就可以在没有进一步运行时检查的情况下被检测到。

数据 JSON

{
   "childNames": ["foo", "bar", "baz"],
   "children": [
      {
         "name": "foo"
      },
      {
         "name": "ba"
      }
   ]
}

JSON 架构

{
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "$id": "https://tbd.com/foo/bar",
    "type": "object",
    "properties": {
       "childNames": {
          "type": "array",
          "items": { "type": "string" }
       },
       "children": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "name": {
                "type": "string",
                "enum": { "$ref": "???" }
              }
            }
          }
       }
    }
}

【问题讨论】:

    标签: json schema jsonschema


    【解决方案1】:

    如果您使用的是 .Net,那么您可以使用 JsonSchema.Net 和 JsonSchema.Net.Data 执行此操作。

    您需要使用定义 data 关键字的自定义词汇表。

    您的架构需要更改为:

    {
      "$schema": "https://gregsdennis.github.io/json-everything/meta/data",
      "$id": "https://tbd.com/foo/bar",
      "type": "object",
      "properties": {
         "childNames": {
            "type": "array",
            "items": { "type": "string" }
         },
         "children": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "name": {
                  "data": {
                    "enum": "#/childNames"
                  }
                }
              }
            }
         }
      }
    }
    

    注意data 关键字所在的??? 以及$schema 关键字中的不同元模式。

    您可以在https://json-everything.net/json-schema 上试用。

    有关其工作原理的信息是here

    如果您不使用 .Net,您可能需要弄清楚如何支持此词汇表(或与您正在使用的库的维护者合作)。

    免责声明:我是 JsonSchema.Net 和其他 json-everything 库的创建者和维护者。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-14
      相关资源
      最近更新 更多