Skip to content

Instantly share code, notes, and snippets.

@nfeldman
Created October 26, 2011 00:42
Show Gist options
  • Select an option

  • Save nfeldman/1315052 to your computer and use it in GitHub Desktop.

Select an option

Save nfeldman/1315052 to your computer and use it in GitHub Desktop.
basic JSON prettify
function simplePrettyJson (str) {
var stack = [], // collect all tokens
word = [], // accumulator to build tokens of more than one char, like an object's keys.
// Not strictly needed but could be useful if we ever allow callbacks
ws = '',
tab = ' ', // 3 spaces are standard and 2 are trendy, but 4 are readable
depth = 0,
inquotes = false,
curr, next, prev;
for (var ii = 0, l = str.length; ii < l; ii++) {
ws = '\n';
prev = curr;
curr = str.charAt(ii);
next = str.charAt(ii + 1);
if (curr == '"' && prev != '\\') {
if (!inquotes) {
inquotes = true;
stack.push(curr)
} else {
stack.push(word.join(''), curr)
word = [];
inquotes = false;
}
} else if (!inquotes) {
switch (curr) {
case '{' :
++depth;
stack.push(curr)
for (var i = 0; i < depth; i++)
ws += tab;
stack.push(ws)
break;
case '[' :
++depth;
stack.push(curr)
if (next != ']') { // we want to keep an empty array on the same line
for (var i = 0; i < depth; i++)
ws += tab;
stack.push(ws)
}
break;
case '}' :
--depth;
for (var i = 0; i < depth; i++)
ws += tab
stack.push(ws)
stack.push(curr)
break;
case ']' :
--depth;
if (prev != '[') { // we want to keep an empty array on the same line
for (var i = 0; i < depth; i++)
ws += tab;
stack.push(ws)
}
stack.push(curr)
break;
case ',' :
stack.push(curr)
if (next != '{') { // this is a personal style preference, not standard
for (var i = 0; i < depth; i++)
ws += tab;
stack.push(ws)
}
break;
default :
stack.push(curr)
}
} else {
word.push(curr)
}
}
return stack.join('')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment