Schema Registry Example - JSON Schema
This page demonstrates how to register a draft 2020-12 JSON Schema in Schema Registry and use the schema_check function in a rule to validate MQTT message payloads. The example republishes only payloads that conform to the schema.
Supported JSON Schema Drafts
Starting from EMQX 6.0.4, Schema Registry supports the following JSON Schema drafts:
- draft-03
- draft-04
- draft-06
- draft 2019-09
- draft 2020-12
EMQX selects the JSON Schema version based on the value of the $schema field. If $schema is omitted, EMQX uses draft-06.
Support for draft 2019-09 and draft 2020-12 has the following limitations:
- Draft 2019-09 does not support
$recursiveRef. - Draft 2020-12 does not support
$dynamicRef. - References to remote schemas are not supported for these two drafts.
If a schema uses an unsupported keyword, validation returns an error instead of silently ignoring the keyword.
Create a JSON Schema
Create a schema that accepts an array containing exactly two integers:
In the EMQX Dashboard, click Smart Data Hub -> Schema Registry in the left navigation menu.
On the Internal tab, click Create.
Configure the following fields:
Name: Enter
json_array.Type: Select JSON Schema.
Schema: Enter the following draft 2020-12 schema:
json{ "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "array", "prefixItems": [ { "type": "integer" }, { "$ref": "#/prefixItems/0" } ], "minItems": 2, "maxItems": 2 }
Click Create.
The prefixItems array defines the schema for each position. The local $ref makes the second item use the same integer schema as the first item. minItems and maxItems require the payload to contain exactly two items.
Create a Rule
Create a rule that republishes messages only when the payload conforms to json_array:
In the Dashboard, click Integration -> Rules in the left navigation menu.
On the Rules page, click Create.
Enter
validate_json_arrayin the Name field.Enter the following statement in the SQL Editor:
sqlSELECT * FROM "t/json" WHERE schema_check('json_array', payload)The
schema_checkfunction returnstruewhen the payload conforms tojson_array. Otherwise, it returnsfalse, and the rule does not execute its action.Click Add Action, and select Republish.
Enter
validated/jsonin the Topic field and${payload}in the Payload field.Click Create.
Test the Rule
Use MQTTX CLI to verify the rule:
Subscribe to the republish topic:
bashmqttx sub -t validated/jsonIn another terminal, publish a payload that conforms to the schema:
bashmqttx pub -t t/json -m '[1, 2]'The subscriber receives
[1, 2]from thevalidated/jsontopic.Publish a payload whose second item is not an integer:
bashmqttx pub -t t/json -m '[1, "two"]'The rule does not execute the republish action, and the subscriber receives no message.
Using schema_check in a rule filters rule execution but does not reject the original MQTT message. To reject or discard nonconforming messages, use Schema Validation.