最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I format JSON code in Monaco Editor with API? - Stack Overflow

programmeradmin1浏览0评论

I am working with monaco editor aka the VS Code engine in a web project.

I am using it to allow users to edit some JSON that has a JSON Schema set, to help give some auto-completion.

When they save their changes and wish to re-edit their work, the JSON that I load back into the editor is converted to a string but this renders the code out on a single line and I would much prefer the JSON to be prettier as if the user right clicks and uses the Format Document command from the context menu or keyboard shortcut etc..

So this

{ "enable": true, "description": "Something" }

Would become this

{
    "enable": true,
    "description:" "Something"
}

Current attempt

I have tried the following but it feels very hacky to use a timeout to wait/guess when the content has loaded

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

});
<script src="/[email protected]/min/vs/loader.js"></script>
<script>
  require.config({
    paths: {
      'vs': '/[email protected]/min/vs'
    }
  });
</script>

<div id="container" style="width:800px;height:600px;border:1px solid grey"></div>

I am working with monaco editor aka the VS Code engine in a web project.

I am using it to allow users to edit some JSON that has a JSON Schema set, to help give some auto-completion.

When they save their changes and wish to re-edit their work, the JSON that I load back into the editor is converted to a string but this renders the code out on a single line and I would much prefer the JSON to be prettier as if the user right clicks and uses the Format Document command from the context menu or keyboard shortcut etc..

So this

{ "enable": true, "description": "Something" }

Would become this

{
    "enable": true,
    "description:" "Something"
}

Current attempt

I have tried the following but it feels very hacky to use a timeout to wait/guess when the content has loaded

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

});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/min/vs/loader.js"></script>
<script>
  require.config({
    paths: {
      'vs': 'https://cdn.jsdelivr.net/npm/[email protected]/min/vs'
    }
  });
</script>

<div id="container" style="width:800px;height:600px;border:1px solid grey"></div>

Does anyone have a better idea or solution to this please?

Share Improve this question edited Jan 28, 2020 at 8:39 Warren Buckley asked Jan 27, 2020 at 21:47 Warren BuckleyWarren Buckley 1,4311 gold badge17 silver badges23 bronze badges 4
  • 1 Can you please show the jsonModel? – Greg Commented Jan 27, 2020 at 21:51
  • No problem will update the example now... and yes I am using vintage tech with AngularJS :-P – Warren Buckley Commented Jan 27, 2020 at 21:59
  • I'm using this in the Azure Portal and right click does not even work, if anyone knows why, please add a comment below. – mckenzm Commented Nov 29, 2022 at 6:09
  • Is this demo of json formatter what you want? Then just use value={formattedJsonString} via @monaco-editor/react. – cwtuan Commented Jan 10, 2023 at 13:21
Add a comment  | 

2 Answers 2

Reset to default 14

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
  });
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/min/vs/loader.js"></script>
<script>
  require.config({
    paths: {
      'vs': 'https://cdn.jsdelivr.net/npm/[email protected]/min/vs'
    }
  });
</script>

<div id="container" style="width:800px;height:600px;border:1px solid grey"></div>

Thanks to https://stackoverflow.com/users/1378051/dalie for reminding me about the extra arguments to JSON.stringify

Answer

Use the tab character for the space argument
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);

I use this function to tidy my code:

tidy() {
  this.monacoEditor.trigger('anyString', 'editor.action.formatDocument')
}

where monacoEditor is result of this.monacoEditor = monaco.editor.create(this.$el, { ...this.editorOptions })

发布评论

评论列表(0)

  1. 暂无评论