如何在 JSON Schema 中使用来自外部文件的定义?

Posted

技术标签:

【中文标题】如何在 JSON Schema 中使用来自外部文件的定义?【英文标题】:How to use definitions from external files in JSON Schema? 【发布时间】:2018-03-05 10:10:56 【问题描述】:

我正在尝试使用 $ref 从另一个 json 架构导入定义,但出现以下错误:

can't resolve reference ../base/definitions.schema.json#/definitions/datetime from id #

"$schema": "http://json-schema.org/draft-06/schema#", “定义”: “约会时间”: “类型”:“字符串” , “姓名”: “类型”:“字符串” , "$schema": "http://json-schema.org/draft-06/schema#", “特性”: “活动”:“类型”:“布尔”, "created_at": "$ref": "../base/definitions.schema.json#/definitions/datetime" , “名称”:“$ref”:“../base/base/definitions.schema.json#/definitions/name”, “updated_at”:“$ref”:“../base/definitions.schema.json#/definitions/datetime” , “必需”:[“名称”], “类型”:“对象”

目录结构:

api - 根据 -- 定义.schema.json - 国家 --国家.schema.json

我通过使用绝对路径、file url 和其他几种路径组合尝试了几种组合。不知道发生了什么。

架构验证器:ajv@5.1.1

【问题讨论】:

【参考方案1】:

您需要使用“addSchema”方法添加架构。 $ref 是相对于“id”属性(draft-06 中的“$id”)解析的,ajv 不(也不能)使用文件路径。

编辑:将 $ref 部分添加到 docs。

【讨论】:

但根据this,我应该可以添加到$ref 的路径。看到这个:$ref can also be a relative or absolute URI, so if you prefer to include your definitions in separate files, you can also do that. 您可以使用路径,正如我所写,它们将使用 id(或 $id)属性中的基本 URI 进行解析。 我有点困惑。你的意思是我必须在$id 属性中定义路径吗?如果定义在多个文件中会发生什么?可以举个例子吗? 您必须在 $id 中定义架构 URI,然后 $ref 将被视为相对于该 URI 的路径 您是否使用 addSchema 添加您尝试访问的架构?第二个模式有 $id 吗? Ajv 不做任何 I/O

以上是关于如何在 JSON Schema 中使用来自外部文件的定义?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 ReactJS 中循环来自外部文件的 JSON 数据?

使用 JSON Schema Form (Retool) 输入多个文件

JSON Schema 是不是可以使用引用外部属性的 if/then/else

如何从 Json schem 文件创建 DataFrame Schema

C# 反序列化 JSON Schema.org 来自网络的食谱

在 PHP 中使用来自 AJAX 请求的 JSON 字符串 [关闭]