重用

重用此架构,因此习惯上(但不是必需)将其放在父架构下的 :definitions
{ "definitions": { "address": { "type": "object", "properties": { "street_address": { "type": "string" }, "city": { "type": "string" }, "state": { "type": "string" } }, "required": ["street_address", "city", "state"] } } }
{ "$ref": "#/definitions/address" }
  1. 转到文档的根目录
  1. 找到钥匙的价值 "definitions"
  1. 在该对象中,找到键的值 "address"

递归

$ref元素可用于创建引用自己的递归模式
{ "$schema": "http://json-schema.org/draft-07/schema#", "definitions": { "person": { "type": "object", "properties": { "name": { "type": "string" }, "children": { "type": "array", "items": { "$ref": "#/definitions/person" }, "default": [] } } } }, "type": "object", "properties": { "person": { "$ref": "#/definitions/person" } } }
相互$ref引用的架构循环可能会在解析器中引起无限循环,因此明确不允许这样做
// error { "definitions": { "alice": { "anyOf": [ { "$ref": "#/definitions/bob" } ] }, "bob": { "anyOf": [ { "$ref": "#/definitions/alice" } ] } } }

$id & $ref

{ "$schema": "http://json-schema.org/draft-07/schema#", "definitions": { "address": { "$id": "#address", "type": "object", "properties": { "street_address": { "type": "string" }, "city": { "type": "string" }, "state": { "type": "string" } }, "required": ["street_address", "city", "state"] } }, "type": "object", "properties": { "billing_address": { "$ref": "#address" }, "shipping_address": { "$ref": "#address" } } }

$ref & Combining schemas

{ "$schema": "http://json-schema.org/draft-06/schema#", "definitions": { "address": { "type": "object", "properties": { "street_address": { "type": "string" }, "city": { "type": "string" }, "state": { "type": "string" } }, "required": ["street_address", "city", "state"] } }, "type": "object", "properties": { "billing_address": { "$ref": "#/definitions/address" }, "shipping_address": { "allOf": [ { "$ref": "#/definitions/address" }, { "properties": { "type": { "enum": [ "residential", "business" ] } }, "required": ["type"] } ] } } }
badge