public
Last active

A JSON pretty printer that produces dense formatted output.

  • Download Gist
dense-json-stringifier.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
/* A JSON pretty printer that produces dense formatted output
*
* Copyright (c) 2012 Brandon Benvie <http://bbenvie.com>
* Released under MIT license.
*/
 
 
/* Accepts same parameters as JSON.stringify, with an optional fourth `options` parameters.
* `options` should be an object with any of the following properties (default values shown):
* {
* maxWidth: 60, // maximum line width in characters before causing output to break into multiple lines
* quotes: '"' // the character used to quote properties and strings. The empty string '' is valid (strings will still be quoted)
* }
*/
 
var stringify = (function(){
var call = Function.prototype.call.bind(Function.prototype.call);
 
var quote = (function(){
var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' };
 
function escaper(a) {
var c = meta[a];
return typeof c === 'string' ? c : '\\u'+('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}
 
return function quote(quotes, string){
escapable.lastIndex = 0;
return quotes+string.replace(escapable, escaper)+quotes;
};
})();
 
 
function multilen(array){
return array.reduce(function(len, item){
return len + item.length;
}, 0);
}
 
 
function J(opts, value){
if (~opts.stack.indexOf(value)) {
throw new Error('circular_structure');
}
 
var stepback = opts.indent,
partial = [],
strlen = 0,
brackets;
 
opts.indent += opts.gap;
opts.stack.push(value);
 
if (value instanceof Array) {
brackets = ['[', ']'];
 
for (var i=0, len = value.length; i < len; i++) {
var prop = str(opts, i, value);
partial[i] = prop === undefined ? 'null' : prop;
strlen += partial[i].length;
}
} else {
var keys = opts.propList || Object.keys(value),
colon = opts.gap ? ': ' : ':';
 
brackets = ['{', '}'];
 
for (var i=0, len=keys.length; i < len; i++) {
var prop = str(opts, keys[i], value);
if (prop !== undefined) {
var val = quote(opts.quotes, keys[i]) + colon + prop;
partial.push(val);
strlen += val.length;
}
}
}
 
if (!partial.length) {
var final = brackets[0] + brackets[1];
} else if (!opts.gap) {
var final = brackets[0] + partial.join(',') + brackets[1];
} else {
var chunks = [[]],
chunk = chunks[0],
currentWidth = 0;
 
for (var i=0; i < partial.length; i++) {
var item = partial[i];
if (item.length < opts.maxWidth && item.length + currentWidth > opts.maxWidth) {
chunk = [];
chunks.push(chunk);
currentWidth = 0;
}
chunk.push(item);
currentWidth += item.length;
}
 
var space = opts.gap ? ' ' : '';
 
var forceNewline = strlen > opts.maxWidth || chunks.some(function(chunk){
return multilen(chunk) > opts.maxWidth;
});
 
var final = chunks.map(function(chunk){
if (forceNewline) {
return chunk.join(',\n' + opts.indent);
}
return chunk.join(',' + space);
}).join(',\n' + opts.indent) + space;
 
 
if (forceNewline) {
final = brackets[0] + '\n' + opts.indent + final + '\n' + stepback + brackets[1];
} else {
final = brackets[0] + space + final + brackets[1];
}
}
 
opts.stack.pop();
opts.indent = stepback;
return final;
}
 
 
 
 
function str(opts, key, holder){
var val = holder[key];
if (val && typeof val === 'object') {
var toJSON = val.toJSON;
if (typeof toJSON === 'function') {
val = call(toJSON, val, key);
}
}
 
if (opts.callback) {
val = call(opts.callback, holder, key, val);
}
 
if (val && typeof val === 'object' && val instanceof Number || val instanceof String || val instanceof Boolean) {
val = val.valueOf();
}
 
 
if (val === null) {
return 'null';
} else if (val === true) {
return 'true';
} else if (val === false) {
return 'false';
}
 
var type = typeof val;
if (type === 'string') {
return quote('"', val);
} else if (type === 'number') {
return val !== val || val === Infinity || val === -Infinity ? 'null' : '' + val;
} else if (type === 'object') {
return J(opts, val);
}
}
 
 
function stringify(value, replacer, space, options){
var opts = Object.create(null);
options || (options = {});
opts.stack = [];
opts.indent = '';
opts.maxWidth = +options.maxWidth || 60;
opts.quotes = typeof options.quotes === 'string' ? options.quotes : '"';
 
if (replacer && typeof replacer === 'object') {
if (typeof replacer === 'function') {
opts.callback = replacer;
} else if (replacer instanceof Array) {
opts.propList = [];
 
for (var i=0; i < replacer.length; i++) {
var item = replacer[i],
type = typeof item;
 
if (type === 'string' || type === 'number' || item instanceof String || item instanceof Number) {
if (!~opts.propList.indexOf(item += '')) {
opts.propList.push(item);
}
}
}
}
}
 
if (space && typeof space === 'object') {
space = space.valueOf();
}
 
if (typeof space === 'string') {
opts.gap = space.slice(0, 10);
} else if (typeof space === 'number') {
space |= 0;
space = space > 10 ? 10 : space < 1 ? 0 : space;
opts.gap = new Array(space + 1).join(' ');
} else {
opts.gap = '';
}
 
return str(opts, '', { '': value });
};
 
stringify.log = function log(quotes, obj){
console.log(stringify(obj, null, ' ', { quotes: quotes }))
};
 
return stringify;
})();
testing.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
// Testing it
 
console.log(stringify({
constructor: [ 'CONSTRUCTOR', 6, 2, 1356 ],
anchor: [ 'ANCHOR', 6, 2, 1389 ],
big: [ 'BIG', 6, 2, 1392 ],
blink: [ 'BLINK', 6, 2, 1395 ],
bold: [ 'BOLD', 6, 2, 1398 ],
fixed: [ 'FIXED', 6, 2, 1401 ],
fontcolor: [ 'FONTCOLOR', 6, 2, 1404 ],
fontsize: [ 'FONTSIZE', 6, 2, 1407 ],
italics: [ 'ITALICS', 6, 2, 1410 ],
link: [ 'LINK', 6, 2, 1413 ],
small: [ 'SMALL', 6, 2, 1416 ],
strike: [ 'STRIKE', 6, 2, 1419 ],
sub: [ 'SUB', 6, 2, 1422 ],
sup: [ 'SUP', 6, 2, 1425 ],
charAt: [ 'CHARAT', 6, 2, 1428 ],
charCodeAt: [ 'CHARCODEAT', 6, 2, 1431 ],
concat: [ 'CONCAT', 6, 2, 1434 ],
indexOf: [ 'INDEXOF', 6, 2, 1437 ],
lastIndexOf: [ 'LASTINDEXOF', 6, 2, 1440 ],
localeCompare: [ 'LOCALECOMPARE', 6, 2, 1443 ],
match: [ 'MATCH', 6, 2, 1446 ],
repeat: [ 'REPEAT', 6, 2, 1449 ],
replace: [ 'REPLACE', 6, 2, 1452 ],
search: [ 'SEARCH', 6, 2, 1455 ],
slice: [ 'SLICE', 6, 2, 1458 ],
split: [ 'SPLIT', 6, 2, 1461 ],
substr: [ 'SUBSTR', 6, 2, 1464 ],
substring: [ 'SUBSTRING', 6, 2, 1467 ],
toLowerCase: [ 'TOLOWERCASE', 6, 2, 1470 ],
toLocaleLowerCase: [ 'TOLOCALELOWERCASE', 6, 2, 1473 ],
toUpperCase: [ 'TOUPPERCASE', 6, 2, 1476 ],
toLocaleUpperCase: [ 'TOLOCALEUPPERCASE', 6, 2, 1479 ],
toString: [ 'TOSTRING', 6, 2, 1482 ],
trim: [ 'TRIM', 6, 2, 1485 ],
valueOf: [ 'VALUEOF', 6, 2, 1488 ]
}, null, ' ', { quotes: "" }));

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.