Ziyuan
Ziyuan

Reputation: 4568

How to reuse an array in a schema?

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?

Upvotes: 0

Views: 106

Answers (1)

Byted
Byted

Reputation: 657

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

Upvotes: 1

Related Questions