Created
November 14, 2012 14:45
-
-
Save sposmen/4072515 to your computer and use it in GitHub Desktop.
Pretty JSON with Javascript (Thanks http://jsfiddle.net/KJQ9K/)
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> | |
<title>Json Pretty</title> | |
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> | |
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script> | |
<script type="text/javascript"> | |
function output(inp) { | |
document.body.appendChild(document.createElement('pre')).innerHTML = inp; | |
} | |
function syntaxHighlight(json) { | |
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); | |
return 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'; | |
} else { | |
cls = 'string'; | |
} | |
} else if (/true|false/.test(match)) { | |
cls = 'boolean'; | |
} else if (/null/.test(match)) { | |
cls = 'null'; | |
} | |
return '<span class="' + cls + '">' + match + '</span>'; | |
}); | |
} | |
</script> | |
<style > | |
pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; } | |
.string { color: green; } | |
.number { color: darkorange; } | |
.boolean { color: blue; } | |
.null { color: magenta; } | |
.key { color: red; } | |
</style> | |
</head> | |
<body> | |
<form method="post"> | |
Ingrese Json | |
<br /> | |
<textarea id="topretty" name="topretty" style="width: 300px; height: 200px"></textarea> | |
<br /> | |
<input type="button" value="Enviar" onClick="output(syntaxHighlight(JSON.stringify($.parseJSON($('#topretty').val()), undefined, 2)));" /> | |
</form> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment