Search code examples
jsonschemamonaco-editor

Setting diagnostics json scheme in runtime


My use case is that have many kinds of messages, for which I can get json schemes from an http request.

I want to update the schema that’s being validated with when I get the response of the http request.

I’m using angular and making an http request, and when I get the schema, I do the same code like the examples and use setDiagnosticsOptions.

I now realize that this kinda requires the defaults to be set before setting the model, but I cannot do that, because I get the schema in runtime and want to load them without reloading the entire site.

Has anyone encountered this use case and solved this somehow?


Solution

  • You can set json defaults after loading the editor. JSON is validated against the new schema immediately.

    Try this code on the monaco playground (just paste it and run)

    var jsonCode = [
        '{',
        '    "p1": "v3",',
        '    "p2": false',
        "}"
    ].join('\n');
    var modelUri = monaco.Uri.parse("a://b/foo.json"); // a made up unique URI for our model
    var model = monaco.editor.createModel(jsonCode, "json", modelUri);
    
    var schema1 = {
            uri: "http://myserver/foo-schema.json", // id of the first schema
            fileMatch: [modelUri.toString()], // associate with our model
            schema: {
                type: "object",
                properties: {
                    p1: {
                        enum: ["v1", "v2"]
                    }
                }
            }
        }
    
    // configure the JSON language support with schemas and schema associations
    monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
        validate: true,
        schemas: [schema1]
    });
    
    monaco.editor.create(document.getElementById("container"), {
        model: model
    });
    
    // try commenting out this line to see that v3 is invalid value for a p1 property
    schema1.schema.properties.p1.enum = ["v1", "v2", "v3"]
    
    // this reloads schemas, you can add/modify and remove schemas this way
    monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
        validate: true,
        schemas: [schema1]
    });
    

    Notice that a new enum value is added after the editor is loaded. If you comment out a line that changes the schema in runtime the value v3 will flag as incorrect.