$anchor : String

$anchor

String

This keyword is used to create plain name fragments that are not tied to any particular structural location for referencing purposes, which are taken into consideration for static referencing.

Kind Identifier
Applies To Any
Dialect 2020-12
Introduced In 2019-09
Vocabulary Core
Specification https://json-schema.org/draft/2020-12/json-schema-core.html#section-8.2.2
Metaschema https://json-schema.org/draft/2020-12/meta/core
Also see

The $anchor keyword is used to assign a unique identifier to a subschema within its schema resource. This identifier can then be referenced elsewhere using the $ref keyword.

  • Its value must be a valid identifier starting with a letter and containing letters, digits, hyphens, underscores, colons, or periods.
  • The $anchor keyword allows for the creation of plain reusable name fragments that aren’t tied to specific structural locations, offering a flexible alternative to using JSON Pointer fragments, which require knowledge of the schema’s structure.
  • An anchor is resolved against the base URI of its schema resource.

Examples

Schema with a named anchor (identifier) Schema
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$ref": "#string",
  "$defs": {
    "string": {
      "$anchor": "string",
      "type": "string"
    }
  }
}
An instance with a string is valid Instance
"Hello World!"
An instance with a number is invalid Instance
44
Schema with identifiers having absolute URI Schema
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "properties": {
    "name": { "$ref": "https://example.com/person/name#name" },
    "age": { "$ref": "https://example.com/person/age#age" }
  },
  "required": [ "name", "age" ],
  "$defs": {
    "name": {
      "$id": "https://example.com/person/name",
      "$anchor": "name",
      "type": "string"
    },
    "age": {
      "$id": "https://example.com/person/age",
      "$anchor": "age",
      "type": "integer"
    }
  }
}
An instance adhering to the schema is valid Instance
{
  "name": "John",
  "age": 55
}
The value of age must be an integer Instance
{
  "name": "foo",
  "age": "bar"
}
Schema with location-independent identifier having base URI change in subschema Schema
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://example.com/base",
  "$ref": "https://example.com/nested#foo",
  "$defs": {
    "foo": {
      "$id": "nested",
      "$anchor": "foo",
      "type": "integer"
    }
  }
}
An instance with integer is valid Instance
99
An instance with boolean is invalid Instance
true
  • Here the URI Reference of foo subschema is resolved to https://example.com/nested and the named anchor is used in the URI fragment to reference this subschema.