如何使用 API 在 Monaco Editor 中格式化 JSON 代码?

War*_*ley 10 javascript json monaco-editor

我正在一个 Web 项目中使用monaco 编辑器(又名VS Code引擎)。

我使用它来允许用户编辑一些具有 JSON 架构集的 JSON,以帮助提供一些自动完成功能。

当他们保存更改并希望重新编辑他们的工作时,我加载回编辑器的 JSON 会转换为字符串,但这会将代码呈现在一行上,我更希望 JSON 更漂亮,就好像用户右键单击并使用上下文菜单或键盘快捷键等中的“设置文档格式”命令。

所以这

{ "enable": true, "description": "Something" }
Run Code Online (Sandbox Code Playgroud)

会变成这样

{
    "enable": true,
    "description:" "Something"
}
Run Code Online (Sandbox Code Playgroud)

目前的尝试

我已经尝试过以下方法,但使用超时来等待/猜测内容何时加载感觉非常hacky

require(['vs/editor/editor.main'], function() {

  // JSON object we want to edit
  const jsonCode = [{
    "enabled": true,
    "description": "something"
  }];

  const modelUri = monaco.Uri.parse("json://grid/settings.json");
  const jsonModel = monaco.editor.createModel(JSON.stringify(jsonCode), "json", modelUri);

  const editor = monaco.editor.create(document.getElementById('container'), {
    model: jsonModel
  });

  // TODO: YUK see if we can remove timeout, as waiting for the model/content to be set is weird
  // Must be some nice native event?!
  // ALSO ITS SUPER JARRING WITH FLASH OF CHANGE
  setTimeout(function() {
    editor.getAction('editor.action.formatDocument').run();
  }, 100);

});
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.jsdelivr.net/npm/monaco-editor@0.19.3/min/vs/loader.js"></script>
<script>
  require.config({
    paths: {
      'vs': 'https://cdn.jsdelivr.net/npm/monaco-editor@0.19.3/min/vs'
    }
  });
</script>

<div id="container" style="width:800px;height:600px;border:1px solid grey"></div>
Run Code Online (Sandbox Code Playgroud)

请问有人对此有更好的想法或解决方案吗?

War*_*ley 12

require(['vs/editor/editor.main'], function() {

  // JSON object we want to edit
  const jsonCode = [{
    "enabled": true,
    "description": "something"
  }];

  const modelUri = monaco.Uri.parse("json://grid/settings.json");
  const jsonModel = monaco.editor.createModel(JSON.stringify(jsonCode, null, '\t'), "json", modelUri);

  const editor = monaco.editor.create(document.getElementById('container'), {
    model: jsonModel
  });
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.jsdelivr.net/npm/monaco-editor@0.19.3/min/vs/loader.js"></script>
<script>
  require.config({
    paths: {
      'vs': 'https://cdn.jsdelivr.net/npm/monaco-editor@0.19.3/min/vs'
    }
  });
</script>

<div id="container" style="width:800px;height:600px;border:1px solid grey"></div>
Run Code Online (Sandbox Code Playgroud)

感谢/sf/users/96463601/提醒我有关 JSON.stringify 的额外参数

回答

使用制表符作为空格参数
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

const jsonModel = monaco.editor.createModel(JSON.stringify(jsonCode, null, '\t'), "json", modelUri);