Monaco JSON Schema Diagnostics
Attach a JSON schema to a Monaco editor model so invalid config keys are flagged inline, with hover docs and completion driven by the schema.
Code
import * as monaco from 'monaco-editor';
const schema = {
type: 'object',
required: ['name', 'version'],
additionalProperties: false,
properties: {
name: { type: 'string', description: 'Package display name' },
version: { type: 'string', pattern: '^\\d+\\.\\d+\\.\\d+$' },
private: { type: 'boolean', default: false },
},
};
monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
validate: true,
allowComments: false,
schemas: [
{
uri: 'https://example.com/schemas/package.schema.json',
fileMatch: ['package.config.json'],
schema,
},
],
});
const model = monaco.editor.createModel(
JSON.stringify({ name: 'demo', version: 'not-semver' }, null, 2),
'json',
monaco.Uri.parse('inmemory://model/package.config.json'),
);
monaco.editor.create(document.getElementById('editor')!, {
model,
automaticLayout: true,
minimap: { enabled: false },
});
const markers = monaco.editor.getModelMarkers({ resource: model.uri });
console.log('marker count:', markers.length);How it works
Three top-level bindings carry the demo state: schema (the JSON Schema under validation), model and markers.
Watch out for
- External dependency:
monaco-editor— install it before running the snippet. - This file imports
monaco-editorand touchesdocument, so it belongs in an editor page, not a Node script.
Applying it
Running the file prints labeled results such as marker count: — the number on that line reflects the markers collected during validation.
Statements that matter
const markers = monaco.editor.getModelMarkers({ resource: model.uri });
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.
FAQ
- Which packages must be installed first?
- Yes. The imports resolve to `monaco-editor`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.