Pretty JSON

Make JSON text look better

  1. // ==UserScript==
  2. // @name Pretty JSON
  3. // @namespace qixinglu.com
  4. // @description Make JSON text look better
  5. // @include http://*/*.json
  6. // @grant none
  7. // @version 0.0.1.20140517140354
  8. // ==/UserScript==
  9.  
  10. var format = function(text) {
  11. var json = JSON.parse(text);
  12. return JSON.stringify(json, null, 4);
  13. };
  14.  
  15. var highlight = function(text) {
  16. // get from http://stackoverflow.com/questions/4810841/json-pretty-print-using-javascript
  17. var json = text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  18. var reg = /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g;
  19. var replace = function (match) {
  20. var cls = 'number';
  21. if (/^"/.test(match)) {
  22. if (/:$/.test(match)) {
  23. cls = 'key';
  24. } else {
  25. cls = 'string';
  26. }
  27. } else if (/true|false/.test(match)) {
  28. cls = 'boolean';
  29. } else if (/null/.test(match)) {
  30. cls = 'null';
  31. }
  32. return '<span class="' + cls + '">' + match + '</span>';
  33. }
  34. return json.replace(reg, replace);
  35. };
  36.  
  37. var addStyle = function(cssText) {
  38. var head = document.querySelector('head');
  39. var style = document.createElement('style');
  40. style.setAttribute('type', 'text/css');
  41. style.textContent = cssText;
  42. head.appendChild(style);
  43. };
  44.  
  45. addStyle(
  46. 'pre {padding: 10px; margin: 10px;}' +
  47. '.string {color: green;}' +
  48. '.number {color: darkorange;}' +
  49. '.boolean {color: blue;}' +
  50. '.null {color: magenta;}' +
  51. '.key {color: red;}'
  52. );
  53.  
  54. document.body.innerHTML = '<pre>' +
  55. highlight(format(document.body.innerHTML)) +
  56. '</pre>';