JSON Formatter

auto format JSON files

  1. // ==UserScript==
  2. // @name JSON Formatter
  3. // @namespace https://greasyfork.org/users/649
  4. // @version 1.0.1
  5. // @description auto format JSON files
  6. // @author Adrien Pyke
  7. // @include /^.*\.json(\?.*)?$/
  8. // @grant GM_getValue
  9. // @grant GM_setValue
  10. // @grant GM_registerMenuCommand
  11. // @require https://cdn.jsdelivr.net/gh/kufii/My-UserScripts@c7f613292672252995cb02a0cab3b6acb18ccac5/libs/gm_config.js
  12. // ==/UserScript==
  13.  
  14. (() => {
  15. 'use strict';
  16.  
  17. const Config = GM_config([
  18. { key: 'tabSize', label: 'Tab Size', type: 'number', min: 0, default: 2 },
  19. { key: 'wordWrap', label: 'Word Wrap', type: 'bool', default: true }
  20. ]);
  21. GM_registerMenuCommand('JSON Formatter: Config', Config.setup);
  22.  
  23. const format = ({ tabSize, wordWrap }) => {
  24. const formatted = JSON.stringify(
  25. JSON.parse(document.body.textContent),
  26. null,
  27. Number(tabSize)
  28. );
  29. document.body.innerHTML = `<code><pre style="${
  30. wordWrap ? 'white-space:pre-wrap;word-break:break-word' : ''
  31. }" id="jsonArea"></pre></code>`;
  32. document.getElementById('jsonArea').textContent = formatted;
  33. };
  34. format(Config.load());
  35. Config.onsave = format;
  36. })();