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.

TypescriptData Integrity

Code

typescriptsnippet
39 lines
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-editor and touches document, 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

FAQ

Which packages must be installed first?
Yes. The imports resolve to `monaco-editor`, which the package manager must provide.