Change record status: 
Project: 
Introduced in branch: 
main
Introduced in version: 
12.1.0
Description: 

The serializer's getJsonSchema() now describes maps (typed data). Before, it returned just a $comment for a map, which matches any value in JSON Schema.

Example:

$definition = MapDataDefinition::create()
  ->setPropertyDefinition('first_name', DataDefinition::create('string')->setLabel(new TranslatableMarkup('First name'))->setRequired(TRUE))
  ->setPropertyDefinition('middle_name', DataDefinition::create('string')->setLabel(new TranslatableMarkup('Middle name')));
$data = \Drupal::typedDataManager()->create($definition);
$schema = \Drupal::service('serializer')->getJsonSchema($data, []);

$schema is then, encoded as JSON:

{
    "type": "object",
    "additionalProperties": false,
    "properties": {
        "first_name": {
            "type": "string",
            "title": "First name"
        },
        "middle_name": {
            "oneOf": [
                {
                    "type": "string"
                },
                {
                    "type": "null"
                }
            ],
            "title": "Middle name"
        }
    },
    "required": [
        "first_name"
    ]
}

The schema describes the map's normalized data with some of the following features:

  • It has one property for each property of the map that isn't internal, set with setInternal().
  • A property whose definition is required is listed in required.
  • A property with a label has that label as its title, as in JSON:API's schemas, and a property without one has no title.

Some maps still get only a $comment, because their normalized data isn't a JSON object with known keys:

  • A map with no property definitions, whose value can be any array.
  • A map whose properties are all internal, which normalizes to an empty array, encoded as [].
  • A map whose properties are named 0, 1, 2 in order, which encodes as a JSON array vs JSON object.

Subclasses of Map, like field items, are unchanged and get the schema they got before. Their normalizers can add keys that aren't properties, which is not supported at this point.

Impacts: 
Module developers