Referencing JSON Schema from json similar way XML

2020-04-12 15:56发布

问题:

When I have defined XML Schema I can then reference it from XML this way saying that that XML must correspond to the referenced schema. This way I can force validation of such XML and I can also provide valuable hint for the person who is going to edit this file, because XML editors supporting XML Schema will use such reference to generate auto-complete, this way making editing much easier.

However I can't see such referencing in JSON Schema documentation. For example: https://json-schema.org/learn/getting-started-step-by-step.html

It looks like it is not part of the standard, or I just can't find it.

Here is an example for XSD Schema with reference usage:

<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>

And here is an XML that uses that Schema by referencing it logical name: 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>

So now anyone can start editing it and, if supported, get auto-complete by their editor based on referenced XSD Schema.

But what about JSON Schema?

If I have JSON schema like this:

{
  "$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" ]
}

And actual JSON like this:

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

Then how can I actually link the JSON to Schema I expect it will correspond to?

回答1:

You are correct, it is not part of the standard.

For JSON returned as an HTTP response, you can note using a header that the response JSON is described by a specific JSON Schema.

https://tools.ietf.org/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"