Skip to content

Instantly share code, notes, and snippets.

@eyalzek
Created March 5, 2015 14:30
Show Gist options
  • Save eyalzek/b29a48547bf4f10fafe8 to your computer and use it in GitHub Desktop.
Save eyalzek/b29a48547bf4f10fafe8 to your computer and use it in GitHub Desktop.
Pretty print JSON (taken from stackoverflow) and an added save method
function syntaxHighlight(json) {
json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
var key;
json = json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
key = match;
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
if (cls === 'key') {
return '<span class="' + cls + '">' + match + '</span>';
} else {
// console.log(key);
return '<span contenteditable="true" id=' + key.replace(":", "") + ' class="' + cls + '">' + match + '</span>';
}
});
return json.replace(/.+> [\[|\{]/g, function(match) {
var i = match.match(/^\s+/g)[0].length;
return match.replace('key', 'key collapse" data-id="' + i);
});
}
function printData(data) {
console.log(data);
var d = JSON.stringify(data, null, 4);
output(syntaxHighlight(d));
}
function output(inp) {
$('.json-container').append($('<pre></pre>').html(inp));
}
function saveData() {
var json = $('pre').html();
return json.replace(/<[^>]*>/g, '');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment