JSON Schema Editor
What is the JSON Schema Editor?
The ai_json_schema form element provides a CodeMirror 6–based JSON editor
with syntax highlighting, line numbers, and real-time JSON linting. It is
designed for editing JSON schemas or any structured JSON data within Drupal
forms.
How can I use the editor?
Use the ai_json_schema form element type in any Drupal form:
$form['json_schema'] = [
'#type' => 'ai_json_schema',
'#title' => $this->t('JSON Schema'),
'#description' => $this->t('Enter a valid JSON schema.'),
'#default_value' => '{"type": "object", "properties": {}}',
];
The element renders a hidden <input> that carries the form value, a fallback
<textarea> for when JavaScript is unavailable, and a CodeMirror editor that
takes over when JS loads. The default value is automatically pretty-printed in
the editor.
Create with AI
Writing a JSON schema by hand is hard, and strict structured output adds its
own rules. Set #ai_generate to offer a Create with AI button:
$form['json_schema'] = [
'#type' => 'ai_json_schema',
'#title' => $this->t('JSON Schema'),
'#ai_generate' => TRUE,
];
The button opens a dialog where the user describes the answer in plain words, and can start from the current schema, an example answer or the fields of a content type. The default chat model writes the schema, which the dialog shows as a list of fields and as JSON. The user can ask for changes, try again, and use the schema, which fills the field.
Generated schemas follow the strict structured output rules: every object
lists all its properties as required and allows no other properties, and
fields that may be missing accept null. The
ai.json_schema_generator service does the work and can be used on its own.
The button only shows to users with the "Create JSON schemas with AI" permission. It is off by default, so existing forms are unchanged.
Graceful fallback
If JavaScript fails to load, the user still sees a plain <textarea> they can
type into. When CodeMirror initializes successfully it hides the fallback
textarea, shows the rich editor, and syncs all changes back to the hidden input
for normal form submission.
Why is the built editor not included?
The built assets are only included for tagged versions of the module. If you use
the branch for development you need to build the assets yourself. For this you
will need to have npm running locally. The minimum required version of node
is 20.14.0.
To build the editor assets follow the instructions:
- Go to
ui/json-schema-editorfolder. - Run
npm install - Run
npm run build - Do not commit the changes from
ui/json-schema-editor/distfolder.