JSON Schema中definitions内的子模式能否引用其他子模式?
关于JSON Schema definitions互相引用的问题
嘿,完全可以这么做!在JSON Schema的definitions里定义的模式,互相引用是非常常见且推荐的做法——这正是definitions设计的核心目的之一:帮你复用重复的Schema片段,让整体结构更简洁、更易于维护。
不过注意你示例里的两个小问题:
- 你写的
$ref: "#definitions/apple"路径格式不对,正确的JSON Pointer语法需要在#后面加斜杠,应该写成#/definitions/apple; - 直接写
"edible": "boolean"不符合JSON Schema规范,需要把属性类型定义放在properties的子对象中。
修正后的合法示例如下:
{ "definitions": { "apple": { "description": "a type of fruit", "type": "object", "properties": { "edible": { "type": "boolean" } } }, "fruit": { "description": "a type of food", "type": "object", "properties": { "edible": { "type": "boolean" }, "items": { "$ref": "#/definitions/apple" } } } } }
只要你的$ref路径符合JSON Pointer的语法规范,就可以自由引用同一个definitions对象里的任何其他定义,完全不用担心出错~
内容的提问来源于stack exchange,提问作者Dorielle
相关产品推荐
相关产品推荐

