Skip to content

Instantly share code, notes, and snippets.

@t8g
Created July 1, 2011 10:19
Show Gist options
  • Save t8g/1058244 to your computer and use it in GitHub Desktop.
Save t8g/1058244 to your computer and use it in GitHub Desktop.
json pretty print
// NOTE : ça utilise le $.each de jquery, mais on peut utiliser n'importe quoi d'autre
// Inspiré de la lib JSON du ZEND Framework
// st : chaine json
var tokens = st.split(/([\{\}\]\[,])/g);
var ind = 0;
var result = '';
$.each(tokens, function(i, token) {
if (token == '') return;
var prefix = new Array(ind+1).join('\t');
if (token == '{' || token == '[') {
ind++;
if (result != '' && result[result.length-1] == '\n') result += prefix;
result += token + '\n';
} else if (token == '}' || token == ']') {
ind--;
prefix = new Array(ind+1).join('\t');
result += '\n' + prefix + token;
} else if (token == ',') {
result += token + '\n';
} else {
result += prefix + token;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment