JSON Beautifier

JSON Beautifier from jsfiddle





JS


if (!library)
   var library = {};

library.json = {
   replacer: function(match, pIndent, pKey, pVal, pEnd) {
      var key = '';
      var val = '';
      var str = '';
      var r = pIndent || '';
      if (pKey)
         r = r + key + pKey.replace(/[": ]/g, '') + ': ';
      if (pVal)
         r = r + (pVal[0] == '"' ? str : val) + pVal + '';
      return r + (pEnd || '');
      },
   prettyPrint: function(obj) {
      var jsonLine = /^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/mg;
      return JSON.stringify(obj, null, 3)
         .replace(/&/g, '&').replace(/\\"/g, '"')
         .replace(/
/g, '>') .replace(jsonLine, library.json.replacer); } }; var account = { active: true, codes: [48348, 28923, 39080], city: "London" }; var planets = [{ name: 'Earth', order: 3, stats: { life: true, mass: 5.9736 * Math.pow(10, 24) } }, { name: 'Saturn', order: 6, stats: { life: null, mass: 568.46 * Math.pow(10, 24) } }]; $('#account').html(library.json.prettyPrint(account)); $('#planets').html(library.json.prettyPrint(planets));


CSS
pre {
   background-color: ghostwhite;
   border: 1px solid silver;
   padding: 10px 20px;
   margin: 20px; 
   }
.json-key {
   color: brown;
   }
.json-value {
   color: navy;
   }
.json-string {
   color: olive;
   }