从 json 引用 JSON 架构,类似方式 XML 引用 XML 架构

Referencing JSON Schema from json similar way XML references XML Schema

当我定义了 XML 架构后,我可以从 XML 引用它,这样说 XML 必须对应于引用的架构。这样我就可以强制验证这样的 XML 并且我还可以为将要编辑此文件的人提供有价值的提示,因为支持 XML 模式的 XML 编辑器将使用这样的引用来生成自动完成,这样编辑就容易多了。

但是我在 JSON 架构文档中看不到这样的引用。 例如:https://json-schema.org/learn/getting-started-step-by-step.html

看起来它不是标准的一部分,或者我找不到它。

这里是 XSD 架构的示例,具有参考用法:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            targetNamespace="http://example.org/definitions/product">
    <xsd:element name="product">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="id" type="xsd:long" maxOccurs="1" minOccurs="1"/>
                <xsd:element name="name" type="xsd:string" maxOccurs="1" minOccurs="1"/>
                <xsd:element name="description" type="xsd:string" minOccurs="0" maxOccurs="1" />
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
</xsd:schema>

这是一个 XML,它通过引用逻辑名称来使用该架构:http://example.org/definitions/product

<product:product xmlns:product="http://example.org/definitions/product">
    <id>1</id>
    <name>One</name>
    <description>The One</description>
</product:product>

所以现在任何人都可以开始编辑它,如果支持,他们的编辑器会根据引用的 XSD 架构自动完成。

但是 JSON 架构呢?

如果我有这样的 JSON 架构:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "http://example.org/definitions/product",
  "title": "product",
  "type": "object",
  "properties": {
    "id": {
      "type": "long"
    },
    "name": {
      "type": "string"
    },
    "description": {
      "type": "string"
    }
  },
  "required": [ "id", "name" ]
}

而实际的 JSON 是这样的:

{
  "id": 1,
  "name": "One",
  "description": "The one"
}

那我怎么才能 link 我期望的 JSON 对应于 Schema?

你是对的,它不是标准的一部分。

对于作为 HTTP 响应返回的 JSON,您可以使用 header 注意到响应 JSON 由特定的 JSON 模式描述。

https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-01#section-10.1

It is RECOMMENDED that instances described by a schema provide a link to a downloadable JSON Schema using the link relation "describedby",
as defined by Linked Data Protocol 1.0, section 8.1
[W3C.REC-ldp-20150226].

In HTTP, such links can be attached to any response using the Link header [RFC8288]. An example of such a header would be:

Link: http://example.com/my-hyper-schema#; rel="describedby"