Simo Mafuxwana
Simo Mafuxwana

Reputation: 3772

Ace-Editor JSON auto format/indent

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

Problem is

Question

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

Upvotes: 22

Views: 41671

Answers (1)

Syjin
Syjin

Reputation: 2809

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.

Upvotes: 68

Related Questions