Ace editor doesn't format the data inside the

2019-05-16 02:10发布

问题:

I have embedded some JSON data inside the editor div.

as here : http://jsfiddle.net/P3TwV/11/

But as shown in the fiddle, the JSON is not being formatted. It simply put the data in one line.

i want the data, that i inputed in single line without any spaces, should get automatically formatted with proper indenting, according to the specified type as here JSON and all the folding and unfolding of the objects inside the editor should get enable.

How do i approach that?

Any answer will help me here. Thank you.

回答1:

Ace doesn't support formatting the code, you can either use beautify.js or browsers built-in json formatter

var val = editor.session.getValue()
var o = JSON.parse(val) // may throw if json is malformed
val = JSON.stringify(o, null, 4) // 4 is the indent size
editor.session.setValue(val)


回答2:

I used beautify and used js_beautify function and work done.



回答3:

As a user mentioned, you should go with beautify.js.

I tried including the Ace Beautifier plugin, but the formatting was completely off.

// https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.6/ext-beautify.js
var beautify = ace.require('ace/ext/beautify');

beautify.beautify(editor.getSession());

Here is an example of hooking JS Beautifier into your existing Ace Editor.

// Variables
var editor = ace.edit('editor');
var txtAra = document.querySelector('textarea[name="editor"]');
var jsbOpts = {
  indent_size : 2
};

// Setup
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/json");
syncEditor();

// Main Logic
setTimeout(formatCode, 1000); // Format sample JSON after 1 second.

// Functions
function syncEditor() {
  editor.getSession().setValue(txtAra.value);
}
function commitChanges() {
  txtAra.value = editor.getSession().getValue();
}
function formatCode() {
  var session = editor.getSession();
  session.setValue(js_beautify(session.getValue(), jsbOpts));
}
.title {
  font-size: 1.67em;
  font-weight: bold;
  text-align: center;
}
#editor {
  height: 75vh;
  width: 100%;
}
textarea[name="editor"] {
  display: none;
}

.as-console-wrapper {
  display: none !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.6/ace.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.6.8/beautify.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css" rel="stylesheet"/>
<div>
  <div class="title">Ace Editor - JSON Format</div>
  <textarea name="editor">{"glossary": {"title": "example glossary","GlossDiv": {"title": "S","GlossList": {"GlossEntry": {"ID": "SGML","SortAs": "SGML","GlossTerm": "Standard Generalized Markup Language","Acronym": "SGML","Abbrev": "ISO 8879:1986","GlossDef": {"para": "A meta-markup language, used to create markup languages such as DocBook.","GlossSeeAlso": ["GML", "XML"]},"GlossSee": "markup"}}}}}</textarea>
  <div id="editor"></div>
</div>