jsonschema - 在运行时设置诊断 json 方案
问题描述
我的用例是有多种消息,我可以从 http 请求中获取 json 方案。
当我收到 http 请求的响应时,我想更新正在验证的架构。
我正在使用 angular 并发出 http 请求,当我获得架构时,我执行与示例相同的代码并使用 setDiagnosticsOptions。
我现在意识到这有点需要在设置模型之前设置默认值,但我不能这样做,因为我在运行时获取架构并希望在不重新加载整个站点的情况下加载它们。
有没有人遇到过这个用例并以某种方式解决了这个问题?
解决方案
您可以在加载编辑器后设置 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
将标记为不正确。
推荐阅读
- python - Python - 以合理的格式放置列表
- ios - 迁移到 firebase v6 后未找到 RNFirebaseNotifications.h。反应原生
- android - 如何使用适用于 Android iOS 和 Web 的 expo SDK 36 创建 dev/staging/preprod/prod 和默认环境?
- swiftui - 在具有 UIViewRepresentable 大小问题的 SwiftUI 中使用 Material MDCCard
- java - 如何修复 java.io.IOException:无法通过代理隧道。代理返回“HTTP/1.1 400 错误请求”?
- mysql - 制作 Discord 验证系统
- javascript - 如何在字符串js中指定的文本之后插入字符?
- c - 将字符串中的数字更改为 int 的函数
- javascript - jQuery 不在 Rails 视图中运行
- opencv - 无法使用包含的 Open CV 标头构建项目