如何修复在同一文档中引用$id时"Can't resolve reference"错误?



我想用 JavaScript 中的 Ajv 验证 JSON 模式。我收到错误:

抛出新的它。MissingRefError(it.baseId, $schema, $message); ^ 错误:无法从 id requestGetGraph 解析引用 #/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" }`);

graph-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" }
]
}
}

如果您在这里查看昨天突然出现的@typescript-eslint相关的构建错误can't resolve reference #/definitions/directiveConfigSchema from id #,只需将"@typescript-eslint/eslint-plugin"降级到版本"5.33.0"。如果你的package.json中没有它,只需添加它(版本中没有^)。删除你的yarn.lock,package-lock.json和node_modules并重建。

更多信息请访问 https://github.com/typescript-eslint/typescript-eslint/issues/5525

这与 URI 解析有关。 检查 https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-01#section-8.2.2

当"$id"设置基本 URI 时,包含该"$id"的对象和 它的所有子架构都可以通过使用从该位置开始的 JSON 指针
fragment 来标识。 即使是进一步更改基本 URI 的
子架构也是如此。 因此,单个
子架构可由多个 URI 访问,每个 URI 由 base 组成 在子架构或父架构中声明的 URI,以及标识从架构对象声明
基到要标识的子架构的路径的 JSON 指针
fragment。 这方面的示例如
显示在第 8.2.4 节中。

由于您指定了前面没有哈希的requestGetGraphs,因此它会像新架构一样解析(因为它不是片段)。在$id前面加上哈希表示它是片段标识符,URI 解析会相应地进行。

你可能也想把requestGetGraphs嵌套在properties里面,对吧?

最新更新