为什么 $ref 在 JSON 模式下有效?
Why is $ref valid under the JSON schema?
我有这个架构:
{
"$schema": "http://json-schema.org/draft-07/schema",
"definitions": {
"person": {
"properties": {
"name": { "type": "string" }
}
},
"employee": {
"$ref": "#/definitions/person",
"properties": {
"salary": { "type": "number" }
}
}
},
"properties": {
"Entry": {
"$ref": "#/definitions/employee"
},
},
}
令人惊讶的是,以下 JSON 在架构下有效:
{
"Entry": {
"name": "John",
"salary": "1234"
}
}
谁能解释一下 $ref
在这里是如何工作的?为什么这个 JSON 有效?
-- 编辑--
我发现如果我改变
"$schema": "http://json-schema.org/draft-07/schema"
至
"$schema": "http://json-schema.org/draft-05/schema"
它将按预期工作,但只有“draft-05”工作;其他像“draft-04”“draft-06”不工作。
在 JSON 草稿 7 之前的架构版本中,当 $ref
关键字与任何其他关键字相邻时,其他关键字将被忽略。
您可以通过将 $ref
包含在 allOf
:
中来解决这个问题
...
"employee": {
"allOf": [ { "$ref": "#/definitions/person" } ],
"properties": {
"salary": { "type": "number" }
}
}
},
...
我有这个架构:
{
"$schema": "http://json-schema.org/draft-07/schema",
"definitions": {
"person": {
"properties": {
"name": { "type": "string" }
}
},
"employee": {
"$ref": "#/definitions/person",
"properties": {
"salary": { "type": "number" }
}
}
},
"properties": {
"Entry": {
"$ref": "#/definitions/employee"
},
},
}
令人惊讶的是,以下 JSON 在架构下有效:
{
"Entry": {
"name": "John",
"salary": "1234"
}
}
谁能解释一下 $ref
在这里是如何工作的?为什么这个 JSON 有效?
-- 编辑--
我发现如果我改变
"$schema": "http://json-schema.org/draft-07/schema"
至
"$schema": "http://json-schema.org/draft-05/schema"
它将按预期工作,但只有“draft-05”工作;其他像“draft-04”“draft-06”不工作。
在 JSON 草稿 7 之前的架构版本中,当 $ref
关键字与任何其他关键字相邻时,其他关键字将被忽略。
您可以通过将 $ref
包含在 allOf
:
...
"employee": {
"allOf": [ { "$ref": "#/definitions/person" } ],
"properties": {
"salary": { "type": "number" }
}
}
},
...