英文:
How to reuse an array in a schema?
问题
以下模式未通过 jsonschema 验证:
$defs:
names:
- n1
- n2
- n3
properties:
name:
enum:
$ref: "#/$defs/names"
使用一个最小的片段,比如 name: "n1"
,jsonschema 会报错 jsonschema.exceptions.SchemaError: ['n1', 'n2', 'n3'] 不是 'object' 或 'boolean' 类型
。
所以,我可以在模式的 $defs
中放一个数组吗?我在 json-schema.org 的教程 中没有看到这个限制。如果不能,我该如何在模式中重用一个数组?
英文:
The following schema doesn't pass the validation with jsonschema
$defs:
names:
- n1
- n2
- n3
properties:
name:
enum:
$ref: "#/$defs/names"
With a minimal fragment such as name: "n1"
, jsonschema will complain jsonschema.exceptions.SchemaError: ['n1', 'n2', 'n3'] is not of type 'object', 'boolean'
.
So can I put an array in a schema's $defs
? I don't see this limitation in the tutorial on json-schema.org. If not, how can I reuse an array in a schema?
答案1
得分: 1
First, the enum
property expects a list of values, not a schema (via the $ref
keyword). Second, the schemas in $defs
(in your example names
) have to be a schema - directly setting a list indeed doesn't work.
To make your example work, you have to use the enum
keyword as part of the $defs
schema like this:
"$defs":
names:
enum:
- n1
- n2
- n2
properties:
name:
"$ref": "#/$defs/names"
This allows you to validate as expected: https://www.jsonschemavalidator.net/s/RGx6COQf
英文:
First, the enum
property expects a a list of values not a schema (via the $ref
keyword). Second, the schemas in $defs
(in your example names
) have to be a schema - directly setting a list indeed doesn't work.
To make your example work, you have to use the enum
keyword as part of the $defs
schema like this:
"$defs":
names:
enum:
- n1
- n2
- n2
properties:
name:
"$ref": "#/$defs/names"
This allows you to validate as expected: https://www.jsonschemavalidator.net/s/RGx6COQf
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论