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, '
  29. $1
  30. ');
  31.  
  32. // add newline before and after square brackets
  33. reg = /([\[\]])/g;
  34. json = json.replace(reg, '
  35. $1
  36. ');
  37.  
  38. // add newline after comma
  39. reg = /(\,)/g;
  40. json = json.replace(reg, '$1
  41. ');
  42.  
  43. // remove multiple newlines
  44. reg = /(
  45.  
  46. )/g;
  47. json = json.replace(reg, '
  48. ');
  49.  
  50. // remove newlines before commas
  51. reg = /
  52. \,/g;
  53. json = json.replace(reg, ',');
  54.  
  55. // optional formatting...
  56. if (!options.newlineAfterColonIfBeforeBraceOrBracket) {
  57. reg = /\:
  58. \{/g;
  59. json = json.replace(reg, ':{');
  60. reg = /\:
  61. \[/g;
  62. json = json.replace(reg, ':[');
  63. }
  64. if (options.spaceAfterColon) {
  65. reg = /\:/g;
  66. json = json.replace(reg, ': ');
  67. }
  68.  
  69. $.each(json.split('
  70. '), function(index, node) {
  71. var i = 0,
  72. indent = 0,
  73. padding = '';
  74.  
  75. if (node.match(/\{$/) || node.match(/\[$/)) {
  76. indent = 1;
  77. } else if (node.match(/\}/) || node.match(/\]/)) {
  78. if (pad !== 0) {
  79. pad -= 1;
  80. }
  81. } else {
  82. indent = 0;
  83. }
  84.  
  85. for (i = 0; i < pad; i++) {
  86. padding += PADDING;
  87. }
  88.  
  89. formatted += padding + node + '
  90. ';
  91. pad += indent;
  92. });
  93.  
  94. return formatted;
  95. };

Report this snippet  

You need to login to post a comment.