gpt4 book ai didi

json - 如何正确引用其他 JSON Schema 文档 ($ref)

转载 作者:行者123 更新时间:2023-12-01 04:53:24 28 4
gpt4 key购买 nike

我已经通读了有关 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 库。我不确定我哪里出错了?

最佳答案

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

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

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

$ref 视为您在浏览器中查看的网页中的链接。 In 可以是绝对的或相对的,就像在您的浏览器中一样。相对的 $ref 将按照与网页上的链接相同的规则进行解析。例如,我希望以下 JSON 中的所有 $ref 都解析为相同的值。 (注意:使用多个 $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

关于json - 如何正确引用其他 JSON Schema 文档 ($ref),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33420463/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com