首页 > 解决方案 > 在运行时设置诊断 json 方案

问题描述

我的用例是有多种消息,我可以从 http 请求中获取 json 方案。

当我收到 http 请求的响应时,我想更新正在验证的架构。

我正在使用 angular 并发出 http 请求,当我获得架构时,我执行与示例相同的代码并使用 setDiagnosticsOptions。

我现在意识到这有点需要在设置模型之前设置默认值,但我不能这样做,因为我在运行时获取架构并希望在不重新加载整个站点的情况下加载它们。

有没有人遇到过这个用例并以某种方式解决了这个问题?

标签: jsonschemamonaco-editor

解决方案


您可以在加载编辑器后设置 json 默认值。JSON 会立即针对新模式进行验证。

在摩纳哥操场上试试这个代码(只需粘贴并运行)

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]
});

请注意,加载编辑器后会添加一个新的枚举值。如果您注释掉在运行时更改架构的行,则该值v3将标记为不正确。


推荐阅读