在同一文档中引用 $id 时如何修复“无法解析引用”错误?

Skv*_*upp 6 javascript jsonschema ajv

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

抛出新的 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" }`);
Run Code Online (Sandbox Code Playgroud)

图请求.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" }
      ]

    }

}
Run Code Online (Sandbox Code Playgroud)

det*_*tay 48

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

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

  • 我评论了这个帖子,因为这是你用谷歌搜索错误时的第一个结果。 (8认同)
  • 更新到“v5.35.1”以使用“@typescript-eslint”包修复 (4认同)
  • 看来最新版本需要修复。刚刚对你的答案投了赞成票。 (2认同)

Rel*_*ual 1

这与 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,对吧?

  • 谢谢你,我解决了。我必须将主根设置为“$id”:“http://example.com/graph-requests.json#”,并在 requestGetGraphs 上的 id 前面添加一个哈希值。然后我必须使用参考进行验证:graph-requests.json#/requestGetGraphs。你能删除你的第一个答案吗?我已经得到了这个理论,并且这篇文章对其他人来说将更容易阅读。 (2认同)