这部分内容是草案4新增内容,而草案3没有。
你可以使用关键字definitions
预先定义部分schema。
// a schema
{
"type": "object",
"properties": {
"street_address": { "type": "string" },
"city": { "type": "string" },
"state": { "type": "string" }
},
"required": ["street_address", "city", "state"]
}
也可以写成:
// a schema
{
"definitions": {
"address": {
"type": "object",
"properties": {
"street_address": { "type": "string" },
"city": { "type": "string" },
"state": { "type": "string" }
},
"required": ["street_address", "city", "state"]
}
}
}
当使用时,我们用$ref
关键字进行引用,$ref
值时一个JSON Pointer。
{ "$ref": "#/definitions/address" }
如下示例:
// a schema
{
"$schema": "http://json-schema.org/draft-04/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": { "$ref": "#/definitions/address" }
}
}
// success
{
"shipping_address": {
"street_address": "1600 Pennsylvania Avenue NW",
"city": "Washington",
"state": "DC"
},
"billing_address": {
"street_address": "1st Street SE",
"city": "Washington",
"state": "DC"
}
}
id
关键字有两个用途:
$ref
的base url被解析。例如,如果有以下声明:
{ "id": "http://foo.bar/schemas/address.json" }
那么:
{ "$ref": "person.json" }
此时,person.json
的url为http://foo.bar/schemas/person.json
。
$ref
的强大之处在于它同组合模式一起使用。
// a schema
{
"$schema": "http://json-schema.org/draft-04/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"]
}]
}
}
}
// failure
{
"shipping_address": {
"street_address": "1600 Pennsylvania Avenue NW",
"city": "Washington",
"state": "DC"
}
}
// success
{
"shipping_address": {
"street_address": "1600 Pennsylvania Avenue NW",
"city": "Washington",
"state": "DC",
"type": "business"
}
}