Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  • 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));
};
like image 382
Simo D'lo Mafuxwana Avatar asked Jan 17 '14 08:01

Simo D'lo Mafuxwana


Video Answer


1 Answers

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.

like image 59
Syjin Avatar answered Oct 07 '22 13:10

Syjin