【问题标题】:How to correctly reference other JSON Schema Documents ($ref)如何正确引用其他 JSON Schema 文档 ($ref)
【发布时间】:2015-10-29 17:05:05
【问题描述】:

我已经阅读了有关 JSON Schema 和 JSON 指针的 RFC,但我仍然在努力理解如何正确引用其他文档。

假设我有以下文件(在磁盘上):

/foo/bar/schema/base.json
/foo/bar/schema/model/model.json

base.json 是这样的:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "/schema/base",
  "title": "Base Response",
  "description": "Schema descriptions of common properties of a response",
  "type": [ "object" ],

  "definitions": {
    "data": {
      "descrpition": "The response data is encapsulated within here",
      "example": "true",
      "type": [ "object", "array", "boolean", "null" ]
    }
  },

  "properties": {
    "data": { "$ref" : "#/definitions/data" }
  }
}

model.json 文件是这样的:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "/schema/model/model",
  "type": "object",

  "$ref": "/schema/base.json"
}

model.json 中的 $ref 值是我要问的。我对标准的理解是,在文档的id和$ref之间,我们应该可以找到文档。

另外,我想知道是否是这样的:

"$ref": "../../base.json"

行得通吗?

但是这些解决方案似乎都不能使用我尝试过的 Python 或 PHP 库。我不确定我哪里出错了?

【问题讨论】:

    标签: json jsonschema json-ref


    【解决方案1】:

    首先,不同的库以不同的方式处理$ref 分辨率,因此您需要遵循它们的特定文档来找出确切的细节。但下面是一些关于$ref 分辨率的一般信息,您可能会觉得有帮助。

    将您的架构文档想象成您在浏览器中查看的网页。 id 代表浏览器 URL 栏中的 URL。它必须是一个完整的绝对规范化 URL,就像在您的浏览器中一样。

    {
      "id": "file:///path/to/project/foo/bar/schema/model/model.json"
    }
    

    $ref 视为您在浏览器中查看的网页中的链接。 In 可以是绝对的或相对的,就像在您的浏览器中一样。相对 $ref 将按照与网页上的链接相同的规则进行解析。例如,我希望以下 JSON 中的所有 $refs 都解析为相同的值。 (注意:$ref 不能使用多个。这只是为了说明。)

    {
      "id": "file:///path/to/project/foo/bar/schema/model/model.json",
      "$ref": "file:///path/to/project/foo/bar/schema/base.json",
      "$ref": "/path/to/project/foo/bar/schema/base.json",
      "$ref": "../model.json"
    }
    

    如果id 不存在,则用于检索架构的URI 应假定为id。在这种情况下file:///path/to/project/foo/bar/schema/model/model.json

    这就是它应该从高层次上工作的方式,但实现方式的实现方式有所不同。有些要求以特定方式设置库。例如,我使用的 PHP 验证器要求您将所有模式注册到 SchemaStore 中,然后才能引用它们。

    参考:http://json-schema.org/latest/json-schema-core.html#anchor27

    【讨论】:

    • 很好的解释 - 谢谢。我认为我落下的主要部分是 ID 字段的含义,以及给定库的复杂性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    • 1970-01-01
    • 2022-07-29
    • 2011-05-25
    相关资源
    最近更新 更多