Created
March 5, 2015 14:30
-
-
Save eyalzek/b29a48547bf4f10fafe8 to your computer and use it in GitHub Desktop.
Pretty print JSON (taken from stackoverflow) and an added save method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function syntaxHighlight(json) { | |
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); | |
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