Search code examples
javascriptjqueryhtmljsonace-editor

Adding Unformatted JSON text to ACE Editor Div with JQuery


I have an instance of an ACE editor within my webpage, and I want to be able to populate it from a text file. To do so, I have set up a dropdown whose onchange function maps to the following:

<script type="text/javascript">
    function popEx(example){
        $.getJSON('testing.txt', function(data){
            var curr_row = $(example).closest('tr');
            var elem = $(curr_row.children()[1]).children()[0];
            var editor = ace.edit(elem);

            editor.getSession().setValue(JSON.parse(data));
            //editor.getSession().setValue(JSON.stringify(data));
        });
    }
 </script>

The issue I'm coming across is automatically formatting the text as JSON. The commented out stringify will paste it just fine, but I'd like it to auto format for me in indented JSON style. Currently the page breaks and gives the error SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data. I'm sure there's an easy way to do this, does anyone have a quick solution?


Solution

  • JSON.stringify indeed supports simple formatting of generated string

    JSON.stringify(data, null, 4) // indent with 4 spaces
    JSON.stringify(data, null, "RTFM") // indent with arbitrary string e.g "\t"
    

    But note that this question doesn't have anything to do with ace and simply searching google for something like format json stringify javascript would give you answer much quicker