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

How can I fix "Can't resolve reference" error when referencing an $id in the same document?

我想在 JavaScript 中针对 JSON 架构验证 JSON 和 Ajv。我收到错误:

抛出新的 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

When an "$id" sets the base URI, the object containing that "$id" and all of its subschemas can be identified by using a JSON Pointer
fragment starting from that location. This is true even of
subschemas that further change the base URI. Therefore, a single
subschema may be accessible by multiple URIs, each consisting of base URI declared in the subschema or a parent, along with a JSON Pointer
fragment identifying the path from the schema object that declares
the base to the subschema being identified. Examples of this are
shown in section 8.2.4.

因为您指定的 requestGetGraphs 前面没有散列,所以它就像一个新架构一样解析(因为它不是片段)。在你的 $id 前加上一个散列表示它是一个片段标识符,并且 URI 解析会相应地发生。

您可能还想将 requestGetGraphs 嵌套在 properties 中,对吗?