如何在模式中重复使用一个数组?

huangapple go评论66阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年2月8日 22:26:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75387207.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定