JSON Schema Form

Edit a JSON Schema, generate a form, and inspect the submitted JSON.

Use the form generator

  1. Choose an example or edit the JSON Schema in the editor.
  2. Select Generate form to compile the edited schema. Invalid JSON or unsupported schema features show an error and keep the last generated form.
  3. Fill the preview and select Submit. Validation errors appear beside fields; valid values appear in Submitted JSON.
  4. Select Reset form to restore schema defaults and clear the submitted result. Selecting another example regenerates the form and clears prior input and output.

The generator accepts a root type: "object" schema. It supports JSON Schema draft 2020-12; when $schema is present, it must name that draft.

Use the published renderer

Import JsonSchemaForm and compileForm from @duskmoon-dev/components/json-schema-form, and import @duskmoon-dev/components/styles.css once. This demo uses the same published renderer.

React example
import { JsonSchemaForm, compileForm } from "@duskmoon-dev/components/json-schema-form";

const compiled = compileForm(schemaFromBackend);

<JsonSchemaForm
  compiled={compiled}
  className="space-y-6"
  value={values}
  onChange={setValues}
  errors={backendErrors}
  onErrorsChange={setBackendErrors}
  onSubmit={sendToBackend}
/>

Alternatively, pass a typed schema directly. Omit value for internal state, optionally initialized by defaultValue. Errors use JSON Pointer keys such as /address/email; onErrorsChange reports validation errors and clears them on edits or reset. Submission runs only after validation and preserves JSON number and boolean types.

The optional className prop adds classes to the generated native <form>, preserving form form-vertical schema-form. The outer wrapper retains its schema-form-container class.

For a LiveView React island, mount inside an element with a stable id and phx-update="ignore", then send the JSON from onSubmit through the LiveView hook. Catch schema compilation errors and validate values again on the backend. Use a new React key to start fresh when replacing the schema.

Fields and submitted values

Schema typeRendered controlSubmitted JSON
stringText inputString; format validates text but does not change the input type.
numberNumber input accepting decimalsNumber
integerNumber input with step 1Integer
booleanCheckboxBoolean
boolean with x-widget: "switch"SwitchBoolean
Primitive enumSelect with a choice promptThe option's original string, number, integer, or boolean type
Primitive enum with x-widget: "radio-group"Radio group for one choiceThe option's original string, number, integer, or boolean type
objectGrouped fields, including nested objectsObject
arrayAdd and remove controls for homogeneous primitive or object itemsArray
array with x-widget: "checkbox-group"Checkbox group for multiple choices from the item enumArray of the options' original primitive values

Untouched optional text and number properties without defaults are initially omitted. Clearing an entered text property leaves an empty string; clearing a numeric property or leaving an enum unchosen omits that property. In an array, clearing a numeric or enum entry keeps its row, and the empty entry must be corrected before submitting; Remove deletes the row. Booleans start as false, arrays start empty, and objects initialize recursively unless a default overrides them. The output is the submitted JSON value, with no string conversion of numeric or boolean controls.

Supported schema keywords

KeywordBehavior
type, properties, itemsDefine the root object, named object fields, and one homogeneous array item schema.
title, descriptionSupply labels and field help text.
requiredList rendered object properties that must be present. Validation runs on submit.
defaultInitialize a matching JSON value. Defaults may still fail other constraints; reset restores them.
enumProvide nonempty choices matching one primitive field type.
x-widgetSelect a compatible property control listed below. Some widgets enforce additional value contracts as well as the JSON Schema constraints.
x-optionsSupply validated option values, labels, optional disabled states, and supported hierarchy children.
x-widget-optionsSupply choice-group orientation, OTP length, Rate count/half-star settings, or Slider bounds/step.
minLength, maxLength, pattern, formatValidate strings on submit; format uses supported draft format validation while rendering a text input.
minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOfValidate numeric values on submit.
minItems, maxItems, uniqueItemsValidate arrays; maxItems also disables Add at the limit.
minProperties, maxPropertiesValidate the number of object properties on submit.
additionalProperties: falseReject additional object properties. Other values are unsupported.
$schema, $id, $commentAccepted metadata; $schema, if specified, must be the draft 2020-12 URL.

Only this rendering subset is accepted. Union or nullable types, $ref, oneOf, anyOf, allOf, conditional schemas, tuple arrays, free-form object properties, and other unlisted keywords are unsupported. Object and array enums are unsupported. Property names __proto__, prototype, and constructor are rejected.

Choose a form control

Add x-widget to a property schema to choose a control. Without it, the default controls above remain in use: format validates a plain string and does not automatically select a date or time picker. Unknown annotations, unsupported options, and incompatible schemas fail generation with their schema location.

Control demoSubmitted JSONSchema and value contract
Cascader
x-widget: "cascader"
Array of string or numeric node valuesComplete enabled path to a leaf; items.enum covers every node.
Checkbox
x-widget: "checkbox"
BooleanBoolean schema; enum may require true.
ColorPicker
x-widget: "color-picker"
StringSix-digit #RRGGBB hex color.
DatePicker
x-widget: "date-picker"
StringReal calendar date in YYYY-MM-DD.
DmDatePicker
x-widget: "dm-date-picker"
StringSame date contract with Dm presentation.
Input
x-widget: "input"
StringString without enum; schema text constraints apply.
InputNumber
x-widget: "input-number"
Number or integerNumeric schema without enum; empty numeric properties are omitted.
Mentions
x-widget: "mentions"
StringFull text, including mentions; optional flat string suggestions.
OtpInput
x-widget: "otp-input"
StringExactly length digits; preserve leading zeroes.
Radio
x-widget: "radio"
Primitive enum valueOne original string, number, integer, or boolean enum value.
Rate
x-widget: "rate"
Number or integercount stars; allowHalf is supported only for number schemas.
Segmented
x-widget: "segmented"
Primitive enum valueAt least one enabled enum option.
Select
x-widget: "select"
Primitive value or unique primitive arrayScalar enum or uniqueItems array with items.enum.
Slider
x-widget: "slider"
Number or integerFinite min < max and positive step; integer schemas use integer settings.
Switch
x-widget: "switch"
BooleanBoolean schema; existing enum restrictions remain enforced.
TimePicker
x-widget: "time-picker"
StringLocal 24-hour HH:mm:ss; no timezone conversion.
Transfer
x-widget: "transfer"
Unique string arrayString item enum supplies selected keys.
TreeSelect
x-widget: "tree-select"
String or number, or unique array of those valuesHierarchy with exact enum coverage; multiple values are independent selections.
Upload
x-widget: "upload"
Unique array of metadata objectsLocal chooser; name, size, type, lastModified only.

The existing Radio group annotation selects one primitive enum value. Checkbox group requires an array with uniqueItems: true and primitive items.enum. Place choice annotations on the array itself; its item schema must not contain widget annotations. All selections preserve the original enum types.

Radio group and Checkbox group support orientation in x-widget-options: "horizontal" places options side by side and wraps them on narrow screens; "vertical" stacks them. Omitting orientation uses vertical. Both example pages show the two directions.

Horizontal radio group schema
{
  "type": "string",
  "title": "Delivery",
  "x-widget": "radio-group",
  "x-widget-options": {
    "orientation": "horizontal"
  },
  "enum": [
    "daily",
    "weekly",
    "monthly"
  ],
  "default": "weekly"
}

Widget contracts apply alongside Ajv validation. Color requires six hex digits; date pickers require real calendar dates; TimePicker requires a complete local 24-hour time; OTP requires exactly its configured number of digits; Cascader requires a complete enabled path to a leaf. An empty Cascader path is valid unless array constraints such as minItems prohibit it. Required fields, enums, numeric bounds, and array constraints remain enforced.

Labels and control options

Use x-options with Radio, Radio group, Checkbox group, Segmented, Select, Transfer, TreeSelect, Cascader, or Mentions. Each option has value, a string label, and optional boolean disabled. Values must match the scalar or array item type and be globally unique; choice options must cover the corresponding enum exactly. Mentions instead accepts optional string suggestions on a string field without enum.

Radio options schema
{
  "type": "integer",
  "title": "Priority",
  "x-widget": "radio",
  "enum": [
    1,
    2
  ],
  "x-options": [
    {
      "value": 1,
      "label": "Normal"
    },
    {
      "value": 2,
      "label": "High"
    }
  ],
  "default": 1
}

Only Cascader and TreeSelect accept children arrays, and both require x-options describing their hierarchy. Cascader submits one ordered path; TreeSelect submits a scalar node value or independent selected nodes in a unique array. Choosing a parent in multiple TreeSelect mode does not select its descendants.

Widget optionsAccepted settings
radio-group, checkbox-grouporientation: "horizontal" or "vertical", default vertical. Horizontal options wrap when needed.
otp-inputlength: integer 1–8, default 6.
ratecount: integer 1–20, default 5. allowHalf: boolean, default false; integer Rate schemas cannot enable it.
sliderFinite min, max, and positive step, with min below max. Defaults use minimum ?? 0, maximum ?? 100, and multipleOf ?? 1. Integer Slider settings must all be integers.

Put these settings in x-widget-options. Other configuration keys and settings on other controls are rejected. Function callbacks, arbitrary component props, remote requests, and JSX option labels are not schema options.

Form presentation

The generator renders a native form with vertical Form.Item labels and help text. It keeps one authoritative JSON value store and uses Ajv validation, preserving typed values and nested objects without a second named-field store.

Submit validates the current values and displays Submitted JSON. Reset form restores schema defaults, clears validation errors, and clears the submitted output.

Defaults, empty values, and reset

Explicit defaults are copied into JSON state and restored on reset. Their types must match the schema, including descendants, but they may still fail other constraints and remain editable. Without explicit defaults, Rate starts at 0, Slider at its minimum, Segmented at its first enabled choice, and ColorPicker at #000000. Booleans, arrays, and objects keep their existing false, empty-array, and recursive defaults.

An ancestor object default is authoritative. If it omits a child, the renderer does not inject that child's natural control value; controls that need a value show a Set action until you act. Normalized or blank control displays do not silently coerce or discard invalid stored defaults. When a control cannot show its candidate faithfully, the raw value is disclosed so it can be corrected before submitting.

Text and mention clearing leaves an empty string. Clearing scalar numeric, date, time, or enum values omits that property; missing required properties must be corrected. Clearing an array entry keeps its row for validation; Remove deletes a row. Empty selections in multiple controls remain arrays. Reset clears validation errors and Submitted JSON.

Upload metadata schema

Upload is a local chooser and submits file metadata. No file contents are serialized and no network upload is performed. Use a unique array of objects with exactly these four required property schemas: string name, integer size, string type, and integer lastModified. The lastModified value is the file's timestamp in milliseconds.

Upload schema
{
  "type": "object",
  "title": "Upload example",
  "additionalProperties": false,
  "properties": {
    "files": {
      "type": "array",
      "title": "Files",
      "x-widget": "upload",
      "default": [],
      "uniqueItems": true,
      "items": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "name": {
            "type": "string"
          },
          "size": {
            "type": "integer",
            "minimum": 0
          },
          "type": {
            "type": "string"
          },
          "lastModified": {
            "type": "integer",
            "minimum": 0
          }
        },
        "required": [
          "name",
          "size",
          "type",
          "lastModified"
        ]
      }
    }
  },
  "required": [
    "files"
  ]
}

Extra property schemas or widget annotations within the metadata item are unsupported. The demo rejects additional metadata properties with additionalProperties: false. Choose or remove files to edit the metadata array; reset restores its empty default.

Examples

Open an example page to start its schema directly, then change the selector or editor to explore other fields.

  • Profile — Combine required text and integer fields with defaults and a choice.
  • String — Validate text length, pattern, and format.
  • Number — Accept a decimal number and validate its bounds.
  • Integer — Require a whole number within a range.
  • Boolean — Use a checkbox and a false default.
  • Enum — Select typed string, number, integer, and boolean values.
  • Nested object — Group related fields under a nested object.
  • Array — Add and remove primitive and object items.
  • Switch — Toggle a boolean with a switch and restore its default.
  • Radio group — Choose one typed enum value from a radio group.
  • Checkbox group — Select multiple typed enum values into a unique array.
  • Cascader — Select a complete path through a hierarchy.
  • Checkbox — Edit a single boolean using a checkbox.
  • ColorPicker — Choose and submit a six-digit hex color.
  • DatePicker — Choose a calendar date as a JSON string.
  • DmDatePicker — Use the date picker with the Dm presentation.
  • Mentions — Suggest names while editing a complete text string.
  • OtpInput — Keep one-time codes as strings with leading zeroes.
  • Radio — Choose one typed value with Radio controls.
  • Rate — Choose whole-star and half-star numeric ratings.
  • Segmented — Choose a typed enum using segmented buttons.
  • Select — Select typed scalar values and unique arrays.
  • Slider — Adjust a bounded numeric value with a slider.
  • TimePicker — Enter a local 24-hour clock time without a timezone.
  • Transfer — Move string choices into a unique selected array.
  • TreeSelect — Select hierarchical values as a scalar or a unique array.
  • Upload — Choose local files and submit their metadata.

Profile

Submitted JSON

Submit the form to see its JSON.