Posted By

penguin999 on 10/12/12


Tagged

javascript json formatter


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

candicom
Beppoi


JSON Formatter


 / Published in: JavaScript
 

This function will format a JSON object or string so that it can be displayed within a browser (within a textarea or "pre" styled element).

Example usage: http://jsfiddle.net/q2gnX/

  1. // Example usage: http://jsfiddle.net/q2gnX/
  2.  
  3. var formatJson = function(json, options) {
  4. var reg = null,
  5. formatted = '',
  6. pad = 0,
  7. PADDING = ' '; // one can also use '\t' or a different number of spaces
  8.  
  9. // optional settings
  10. options = options || {};
  11. // remove newline where '{' or '[' follows ':'
  12. options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false;
  13. // use a space after a colon
  14. options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true;
  15.  
  16. // begin formatting...
  17. if (typeof json !== 'string') {
  18. // make sure we start with the JSON as a string
  19. json = JSON.stringify(json);
  20. } else {
  21. // is already a string, so parse and re-stringify in order to remove extra whitespace
  22. json = JSON.parse(json);
  23. json = JSON.stringify(json);
  24. }
  25.  
  26. // add newline before and after curly braces
  27. reg = /([\{\}])/g;
  28. json = json.replace(reg, '\r\n$1\r\n');
  29.  
  30. // add newline before and after square brackets
  31. reg = /([\[\]])/g;
  32. json = json.replace(reg, '\r\n$1\r\n');
  33.  
  34. // add newline after comma
  35. reg = /(\,)/g;
  36. json = json.replace(reg, '$1\r\n');
  37.  
  38. // remove multiple newlines
  39. reg = /(\r\n\r\n)/g;
  40. json = json.replace(reg, '\r\n');
  41.  
  42. // remove newlines before commas
  43. reg = /\r\n\,/g;
  44. json = json.replace(reg, ',');
  45.  
  46. // optional formatting...
  47. if (!options.newlineAfterColonIfBeforeBraceOrBracket) {
  48. reg = /\:\r\n\{/g;
  49. json = json.replace(reg, ':{');
  50. reg = /\:\r\n\[/g;
  51. json = json.replace(reg, ':[');
  52. }
  53. if (options.spaceAfterColon) {
  54. reg = /\:/g;
  55. json = json.replace(reg, ': ');
  56. }
  57.  
  58. $.each(json.split('\r\n'), function(index, node) {
  59. var i = 0,
  60. indent = 0,
  61. padding = '';
  62.  
  63. if (node.match(/\{$/) || node.match(/\[$/)) {
  64. indent = 1;
  65. } else if (node.match(/\}/) || node.match(/\]/)) {
  66. if (pad !== 0) {
  67. pad -= 1;
  68. }
  69. } else {
  70. indent = 0;
  71. }
  72.  
  73. for (i = 0; i < pad; i++) {
  74. padding += PADDING;
  75. }
  76.  
  77. formatted += padding + node + '\r\n';
  78. pad += indent;
  79. });
  80.  
  81. return formatted;
  82. };

Report this snippet  

You need to login to post a comment.