javascript - 在同一文档中引用 $id 时,如何解决“无法解析引用”错误?
问题描述
我想在 JavaScript 中使用 Ajv 针对 JSON 模式验证 JSON。我得到错误:
throw new it.MissingRefError(it.baseId, $schema, $message); ^ 错误:无法从 id requestGetGraphs 解析参考 #/definitions/requestGraph
删除对其他架构的引用时: { "$ref" : "#/definitions/requestGraph" } 错误消失。
JavaScript 代码:
ajv.addSchema(require('./json-schema/graph-response'), 'graph-response.json');
ajv.validate('requestGetGraphs', `{"type" : "requestGetGraphs", "space" : "config", "v" : 1.1, "id" : "dsaf" }`);
图-request.json:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id" : "graph-requests.json",
"definitions": {
"requestGraph" : {
"$id" : "#/definitions/requestGraph",
"allOf" : [
{ "$ref" : "call.json/#/definitions/request" },
{
"properties": {
"space": {
"$id" : "#requestGraph/properties/space",
"type": "string",
"const": "config"
}
}
}
]
}
},
"requestGetGraphs" : {
"$id" : "requestGetGraphs",
"type" : "object",
"allOf" : [
{
"properties": {
"action": {
"$id" : "#requestGetGraphs/properties/action",
"type": "string",
"const": "requestGetGraphs"
}
}
},
{ "$ref" : "#/definitions/requestGraph" }
]
}
}
解决方案
这与 URI 解析有关。检查https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-01#section-8.2.2
当“$id”设置基本 URI 时,可以使用从该位置开始的 JSON 指针片段来识别包含该“$id”的对象及其所有子模式。即使是
进一步更改基本 URI 的子模式也是如此。因此,单个
子模式可以由多个 URI 访问,每个 URI 都包含在子模式或父级中声明的基本 URI,以及一个 JSON 指针
片段,该片段标识从声明
基本的模式对象到被识别的子模式的路径。
8.2.4 节显示了这方面的示例。
因为您requestGetGraphs
在前面没有指定哈希,所以它解析为一个新模式(因为它不是片段)。在 $id 前面加上一个哈希表示它是一个片段标识符,并且 URI 解析会相应地发生。
你可能也想在requestGetGraphs
里面筑巢properties
,对吧?
推荐阅读
- python - 将多个 csv 与“日期时间”列结合起来
- c++ - 不能在两个重叠的结构上使用初始化列表
- php - 未定义的属性:Cartalyst\Stripe\Stripe::$subscriptions
- java - Java eBay SDK - 无法初始化类 com.ebay.sdk.SdkAPIInterfaceServiceLocator
- react-native - 在useEffect中反应Native setState不触发重新渲染
- react-hooks - 为什么每个组件的 useRef 和 Set 每次渲染计数 2 次而不是 1 次?
- pentaho - Pentaho bi server 4.0.0 GA 在意外关闭后停止工作
- mysql - 根据列值添加计数列
- javascript - 本地存储不断循环.. React useffects
- java - HttpUrlConnection 上传文件失败