首页 > 解决方案 > 在同一文档中引用 $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" }
      ]

    }

}

标签: javascriptjsonschemaajv

解决方案


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


推荐阅读