Implementation using native Json.stringify
<textarea name="" id="myTA" cols="30" rows="10"></textarea><script> var myTA = document.getElementById("myTA"); myTA.value = JSON.stringify({"aaa":123,"bbb":456}, null, 4)</script>
Two own Write function realization
https://jsfiddle.net/q2gnX/
Online preview
//Notes://-json2.js is not needed if browser supports json.stringify and Json.parse natively//-JQuery is only used to place the results//colon; colon, pad; fillvarFormatjson= function(JSON,Options{ varReg= NULL,Formatted= "',Pad= 0,PADDING= "'; //One can also use ' \ t ' or a different number of spaces //Optional SettingsOptions=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 ... //Make sure we start with the JSON as a string if(typeofJson!== ' String '){Json= JSON.stringify(JSON); } //parse and stringify in order to remove extra whitespace //json = Json.stringify (Json.parse (JSON)), extra spaces can be removedJson= JSON.Parse(JSON);Json= JSON.stringify(JSON); //Add newline before and after curly bracesReg= /([\{\}])/g;Json= JSON.Replace(reg, '\ r \ n $\ r \ n'); //Add newline before and after square bracketsReg= /([\[\]])/g;Json= JSON.Replace(reg, '\ r \ n $\ r \ n'); //Add newline after commaReg= /(\,)/g;Json= JSON.Replace(reg, ' $\ r \ n'); //Remove multiple newlinesReg= /(\r\n\r\n)/g;Json= JSON.Replace(reg, '\ r \ n'); //Remove newlines before commasReg= /\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{ varI= 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; }); returnFormatted;};varJson= {};//Display formatted JSON (as JSON object)Json= {"a":{"AA":[1,2,{"AAA":"ABC","BBB":"DEFGH","CCC":987},[ -, $, -,{"One":1,"both":"II","three":"three"}, +]],"BB":"XYZ","CCC":777},"B":["QQQ","www","Eee"],"C":"Hello","D":12345};$(' #formattedJson1 ').text(Formatjson(JSON));//Display formatted JSON (from JSON string)Json= ' {' a ': {' AA ': [1, 2, {' AAA ': ' abc ', '+ ' BBB ': ' DEFGH ', ' CCC ': 987}, [ +]+ ' $, ' {' One ': 1, ' One ': ' II ', ' three '+ ': ' Three '}, +] '+ '], '+ ' BB ': "XYZ", "CCC": 777}, "B": ["QQQ", "www", '+ " Eee"], "C": "Hello", "D": 12345} ';$(' #formattedJson2 ').text(Formatjson(JSON));
js-formatting JSON