P.Y.
P.Y.

Reputation: 147

Restricting values with "enum" for a property typed with "$ref"

I have a base schema base.json that defines a type named foobar:

{
  "definitions": {
    "foobar": {
      "type": "string"
    }
  }
}

I then have another schema instance.json that builds on that type and attempts to restrict its potential values:

{
  "type": "object",
  "properties": {
    "raboof": {
      "$ref": "base.json#/definitions/foobar",
      "enum": [
        "this is a foobar!"
      ]
    }
  }
}

If I try to validate the following file wrong_data.json:

{
  "raboof": "not really a foobar..."
}

my validation tool reports no error.

I do get an error if I change "$ref": "base.json#/definitions/foobar" to "type": "string" in instance.json though.

Am I holding it wrong?

Upvotes: 0

Views: 202

Answers (1)

Relequestual
Relequestual

Reputation: 12355

The JSON Schema core specification for draft-7 (current latest) states the following in the section about $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

Note specifically that you can't use $ref with other keywords in the same object, as other keys in that object will be ignored.

You can get around this limitation by wrapping in an allOf...

{
  "allOf": [
    { "$ref": "base.json#/definitions/foobar" },
    { "enum": [ "this is a foobar!" ] }
  ]
}

This will be allowed in draft-8 so the work around will no longer be required, but it's not yet released.

Upvotes: 1

Related Questions