| Var formatJson = function (json, options ){ Var reg = null, Formatted = '', Pad = 0, PADDING = ''; // One can also use '\ t' or a different number of spaces // Optional settings Options = options | {}; // Remove newline where '{' or '['follows ':' Options. newlineAfterColonIfBeforeBraceOrBracket = (options. newlineAfterColonIfBeforeBraceOrBracket = true )? True: false; // Use a space after a colon Options. spaceAfterColon = (options. spaceAfterColon = false )? False: true; // Begin formatting... If (typeof json! = 'String '){ // Make sure we start with the JSON as a string Json = JSON. stringify (json ); } Else { // Is already a string, so parse and re-stringify // In order to remove extra whitespace Json = JSON. parse (json ); Json = JSON. stringify (json ); } // Add newline before and after curly braces Reg =/([\ {\}])/g; Json = json. replace (reg, '\ r \ n $1 \ r \ n '); // Add newline before and after square brackets Reg =/([\ [\])/g; Json = json. replace (reg, '\ r \ n $1 \ r \ n '); // Add newline after comma Reg =/(\,)/g; Json = json. replace (reg, '$1 \ r \ n '); // Remove multiple newlines Reg =/(\ r \ n)/g; Json = json. replace (reg, '\ r \ n '); // Remove newlines before commas Reg =/\ r \ n \,/g; Json = json. replace (reg ,','); // Optional formatting... If (! Options. newlineAfterColonIfBeforeBraceOrBracket ){ Reg =/\: \ r \ n \ {/g; Json = json. replace (reg ,':{'); Reg =/\: \ r \ n \ [/g; Json = json. replace (reg ,':['); } If (options. spaceAfterColon ){ Reg =/\:/g; Json = json. replace (reg ,':'); } $. Each (json. split ('\ r \ n'), function (index, node ){ Var I = 0, Indent = 0, Padding = ''; If (node. match (/\ {$/) | node. match (/\ [$ /)){ Indent = 1; } Else if (node. match (/\}/) | node. match (/\]/) { If (pad! = 0 ){ Pad-= 1; } } Else { Indent = 0; } For (I = 0; I <pad; I ++ ){ Padding + = PADDING; } Formatted + = padding + node + '\ r \ n '; Pad + = indent; }); Return formatted; }; |