简体   繁体   English

Ace-Editor JSON自动格式/缩进

[英]Ace-Editor JSON auto format/indent

I have just started using Ace Editor. 我刚开始使用Ace Editor。 According to the doc "the editor supports plain text mode. All other language modes are available as separate modules, loaded on demand..." and this is how a JavaScript mode is set editor.getSession().setMode("ace/mode/javascript"); 根据文档 “编辑器支持纯文本模式。所有其他语言模式都可以作为单独的模块使用,按需加载......”这就是如何设置JavaScript模式editor.getSession().setMode("ace/mode/javascript"); this only works for highlighting syntax. 这仅适用于突出显示语法。

In my case I am working with JSON - editor.getSession().setMode("ace/mode/json") 在我的情况下,我正在使用JSON - editor.getSession().setMode("ace/mode/json")

What I am trying to achieve is 我想要实现的是

  • Display a nicely formatted JSON response 显示格式良好的JSON响应

Problem is 问题是

  • Ace Editor can't seem to handle JS objects or JSON on editor.setValue() it has to be converted to a string Ace Editor似乎无法在editor.setValue()上处理JS对象或JSON,它必须转换为字符串

Question

  • How do I set auto format/indentation on the string which is placed on <div id="editor"></div> ? 如何在<div id="editor"></div>上的字符串上设置自动格式/缩进?

HTML: HTML:

<div id="editor"></div>

SCRIPT: jsonDoc is data from the server 脚本: jsonDoc是来自服务器的数据

$scope.getData = function (jsonDoc) {
  var editor = ace.edit("editor");
  editor.getSession().setMode("ace/mode/json");
  editor.setTheme("ace/theme/twilight");
  editor.getSession().setTabSize(2);
  editor.getSession().setUseWrapMode(true);
  editor.setValue(JSON.stringify(jsonDoc));
};

To format your JSON string you can use the additional parameters of JSON.stringify . 要格式化JSON字符串,可以使用JSON.stringify的其他参数。 Try something like 尝试类似的东西

editor.setValue(JSON.stringify(jsonDoc, null, '\t'));

The third parameter is used for the indention per level. 第三个参数用于每个级别的缩进。 (Might vary in different implementations). (可能在不同的实现中有所不同)。 See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify for examples. 有关示例,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

You can also toggle display options from ace.js file. 您还可以从ace.js文件切换显示选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM