2

I'm trying to get formatting right for the Ace (Ajax.org Cloud9 Editor) so I am parsing through the Json pulled from the @Model in an MVC view like so:

var model = JSON.stringify(@Html.Raw(Json.Encode(Model)));

var comma = model.replace(/,/g, ",\r\n");
var curlyBracket = comma.replace(/{/g, "{\r\n");
var colonCurlyBracket = bracket.replace(/:{/g, ':\r\n\{');
var bracketCurlyBracket = colonCurlyBracket.replace(/:\[{/g, ':\r\n\[{');

editor.setValue(bracketCurlyBracket, -1);

The problem is this doesn't do any indents to keep the formatting correct, it just puts carriage returns and new lines. I tried using:

var comma = model.replace(/,/g, ",\r\n\"); 
var curlyBracket = comma.replace(/{/g, "{\r\n\"); 
var colonCurlyBracket = bracket.replace(/:{/g, ':\r\n\\{'); 
var bracketCurlyBracket = colonCurlyBracket.replace(/:\[{/g, ':\r\n\\[{');

but the extra "\" gives me the error "Unterminated string constant" on the first two lines and on the second two lines it just adds a "\" to the editor. I need the lines to continue so that the indents get put in and the formatting works. How do I do this?

Jeff Mcbride
  • 453
  • 2
  • 6
  • 19
  • Are you trying to pretty-print the json? [Related](http://stackoverflow.com/questions/4810841/how-can-i-pretty-print-json-using-javascript) – James Apr 19 '16 at 16:42
  • No. Just need the formatting to look proper so it's easier to read. – Jeff Mcbride Apr 19 '16 at 16:50
  • 1
    Please look at the third parameter for JSON.stringify, that might do it all for you. – James Apr 19 '16 at 16:52

1 Answers1

0

Thank to James here's the answer:

The third parameter for JSON.stringify accomplishes the task of formatting properly so it should look like this:

var model = JSON.stringify(@Html.Raw(Json.Encode(Model)), null, ' ');
editor.setValue(model, -1);

The 3rd parameter (' ') takes spaces and the number of spaces determines the number of indents (I.E. 3 spaces = 3 indents):

"filters": [
            {
                "id": "LastName",
                "label": "LastName",
                "type": "string",
                "operators": [
                    "equal",
                    "not_equal",
                    "begins_with",
                    "not_begins_with",
                    "contains",
                    "not_contains",
                    "ends_with",
                    "not_ends_with"
                ]
            }
           ]

Hope this helps someone else.

Jeff Mcbride
  • 453
  • 2
  • 6
  • 19