├── README.md └── json-format.js /README.md: -------------------------------------------------------------------------------- 1 | json-format 2 | ========== 3 | 4 | #### JSON Pretty Printer for JavaScript #### 5 | 6 | I didn't like the "pretty" formatting of JSON.stringify() so I put this together. 7 | It is loosely based on a [comment at php.net](http://www.php.net/manual/en/function.json-encode.php#80339). 8 | 9 | 10 | ### Usage ### 11 | 12 | var formattedJSONString = JSONFormat( someJSONString ); -------------------------------------------------------------------------------- /json-format.js: -------------------------------------------------------------------------------- 1 | /* 2 | json-format v.1.1 3 | http://github.com/phoboslab/json-format 4 | 5 | Released under MIT license: 6 | http://www.opensource.org/licenses/mit-license.php 7 | */ 8 | 9 | (function(window) { 10 | var p = [], 11 | push = function( m ) { return '\\' + p.push( m ) + '\\'; }, 12 | pop = function( m, i ) { return p[i-1] }, 13 | tabs = function( count ) { return new Array( count + 1 ).join( '\t' ); }; 14 | 15 | window.JSONFormat = function( json ) { 16 | p = []; 17 | var out = "", 18 | indent = 0; 19 | 20 | // Extract backslashes and strings 21 | json = json 22 | .replace( /\\./g, push ) 23 | .replace( /(".*?"|'.*?')/g, push ) 24 | .replace( /\s+/, '' ); 25 | 26 | // Indent and insert newlines 27 | for( var i = 0; i < json.length; i++ ) { 28 | var c = json.charAt(i); 29 | 30 | switch(c) { 31 | case '{': 32 | case '[': 33 | out += c + "\n" + tabs(++indent); 34 | break; 35 | case '}': 36 | case ']': 37 | out += "\n" + tabs(--indent) + c; 38 | break; 39 | case ',': 40 | out += ",\n" + tabs(indent); 41 | break; 42 | case ':': 43 | out += ": "; 44 | break; 45 | default: 46 | out += c; 47 | break; 48 | } 49 | } 50 | 51 | // Strip whitespace from numeric arrays and put backslashes 52 | // and strings back in 53 | out = out 54 | .replace( /\[[\d,\s]+?\]/g, function(m){ return m.replace(/\s/g,''); } ) 55 | .replace( /\\(\d+)\\/g, pop ) // strings 56 | .replace( /\\(\d+)\\/g, pop ); // backslashes in strings 57 | 58 | return out; 59 | }; 60 | })(window); --------------------------------------------------------------------------------