$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.

Value This keyword must be set to a string starting with a letter and containing letters, digits, hyphens, underscores, colons, or periods
Kind Identifier
Applies To Any
Dialect 2020-12
Changed In None
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
Official Tests draft2020-12/anchor.json
Default None
Annotation None
Affected By None
Affects
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.

  • 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"
    }
  }
}
Valid An instance with a string is valid Instance
"Hello World!"
Invalid 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"
    }
  }
}
Valid An instance adhering to the schema is valid Instance
{
  "name": "John",
  "age": 55
}
Invalid 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"
    }
  }
}
Valid An instance with integer is valid Instance
99
Invalid 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.