使用“$ref”输入的 属性 限制 "enum" 的值
Restricting values with "enum" for a property typed with "$ref"
我有一个基本架构 base.json
,它定义了一个名为 foobar
:
的类型
{
"definitions": {
"foobar": {
"type": "string"
}
}
}
然后我有另一个模式 instance.json
构建在该类型上并试图限制它的潜在值:
{
"type": "object",
"properties": {
"raboof": {
"$ref": "base.json#/definitions/foobar",
"enum": [
"this is a foobar!"
]
}
}
}
如果我尝试验证以下文件 wrong_data.json
:
{
"raboof": "not really a foobar..."
}
我的验证工具报告没有错误。
不过,如果我在 instance.json
中将 "$ref": "base.json#/definitions/foobar"
更改为 "type": "string"
,我确实会收到错误消息。
我是不是看错了?
JSON draft-7 的架构核心规范(当前最新版本)在有关 $ref
...
的部分中陈述了以下内容
An object schema with a "$ref" property MUST be interpreted as a
"$ref" reference. The value of the "$ref" property MUST be a URI
Reference. Resolved against the current URI base, it identifies the
URI of a schema to use. All other properties in a "$ref" object MUST
be ignored.
https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-01#section-8.3
请特别注意,您不能将 $ref
与同一对象中的其他关键字一起使用,因为该对象中的其他键将被忽略。
您可以通过包装在 allOf
...
中来绕过此限制
{
"allOf": [
{ "$ref": "base.json#/definitions/foobar" },
{ "enum": [ "this is a foobar!" ] }
]
}
草案 8 中允许这样做,因此不再需要变通方法,但它尚未发布。
我有一个基本架构 base.json
,它定义了一个名为 foobar
:
{
"definitions": {
"foobar": {
"type": "string"
}
}
}
然后我有另一个模式 instance.json
构建在该类型上并试图限制它的潜在值:
{
"type": "object",
"properties": {
"raboof": {
"$ref": "base.json#/definitions/foobar",
"enum": [
"this is a foobar!"
]
}
}
}
如果我尝试验证以下文件 wrong_data.json
:
{
"raboof": "not really a foobar..."
}
我的验证工具报告没有错误。
不过,如果我在 instance.json
中将 "$ref": "base.json#/definitions/foobar"
更改为 "type": "string"
,我确实会收到错误消息。
我是不是看错了?
JSON draft-7 的架构核心规范(当前最新版本)在有关 $ref
...
An object schema with a "$ref" property MUST be interpreted as a
"$ref" reference. The value of the "$ref" property MUST be a URI
Reference. Resolved against the current URI base, it identifies the
URI of a schema to use. All other properties in a "$ref" object MUST be ignored.
https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-01#section-8.3
请特别注意,您不能将 $ref
与同一对象中的其他关键字一起使用,因为该对象中的其他键将被忽略。
您可以通过包装在 allOf
...
{
"allOf": [
{ "$ref": "base.json#/definitions/foobar" },
{ "enum": [ "this is a foobar!" ] }
]
}
草案 8 中允许这样做,因此不再需要变通方法,但它尚未发布。