Ace-Editor JSON auto format/indent

Simo D'lo Mafuxwana picture Simo D'lo Mafuxwana · Jan 17, 2014 · Viewed 28.4k times · Source

I have just started using 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"); this only works for highlighting syntax.

In my case I am working with JSON - editor.getSession().setMode("ace/mode/json")

What I am trying to achieve is

  • Display a nicely formatted JSON response

Problem is

  • Ace Editor can't seem to handle JS objects or JSON on editor.setValue() it has to be converted to a string

Question

  • How do I set auto format/indentation on the string which is placed on <div id="editor"></div>?

HTML:

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

SCRIPT: jsonDoc is data from the server

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

Answer

Syjin picture Syjin · Jan 17, 2014

To format your JSON string you can use the additional parameters of 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.

You can also toggle display options from ace.js file.