js-formatting JSON

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.