index.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. var JSONFormatter = require('../dist/json-formatter.js').default;
  2. var live = document.getElementById('live');
  3. var hoverPreviewEnabledCheckbox = document.getElementById('hoverPreviewEnabled');
  4. function render() {
  5. live.style.backgroundColor = 'transparent';
  6. var result = document.getElementById('live-result');
  7. try {
  8. var formatter = new JSONFormatter(JSON.parse(live.value), 1, { hoverPreviewEnabled: hoverPreviewEnabledCheckbox.checked });
  9. result.innerHTML = '';
  10. result.appendChild(formatter.render());
  11. } catch (e) {
  12. live.style.backgroundColor = 'rgba(255, 87, 34, 0.35)';
  13. }
  14. }
  15. live.addEventListener('keyup', render);
  16. hoverPreviewEnabledCheckbox.addEventListener('change', render);
  17. render();
  18. var complex = {
  19. numbers: [
  20. 1,
  21. 2,
  22. 3
  23. ],
  24. boolean: true,
  25. 'null': null,
  26. number: 123,
  27. anObject: {
  28. a: 'b',
  29. e: 'd',
  30. c: 'f\"'
  31. },
  32. string: 'Hello World',
  33. url: 'https://github.com/mohsen1/json-formatter-js',
  34. date: new Date(),
  35. func: function add(a, b) { return a + b; }
  36. };
  37. var deep = { a: { b: { c: { d: {} } } } };
  38. var examples = [
  39. { title: 'Complex', json: complex },
  40. { title: 'Number', json: 42 },
  41. { title: 'null', json: null },
  42. { title: 'Empty Object', json: Object.create(null) },
  43. { title: 'Empty Array', json: [] },
  44. { title: 'Deep', json: deep },
  45. { title: 'Dark', json: complex, config: { theme: 'dark' } },
  46. { title: 'Sorted Keys', json: complex, config: { sortPropertiesBy: (a, b) => a > b } }
  47. ];
  48. var result = document.querySelector('.result');
  49. examples.forEach(function (example) {
  50. var title = document.createElement('h3');
  51. var formatter = new JSONFormatter(example.json, 1, example.config);
  52. title.innerText = example.title;
  53. result.appendChild(title)
  54. var el = formatter.render();
  55. if (example.config && example.config.theme === 'dark') {
  56. el.style.backgroundColor = '#1E1E1E';
  57. }
  58. result.appendChild(el);
  59. });
  60. fetch('demo/giant.json').then(function (resp) {
  61. resp.json().then(function (giant) {
  62. var giantFormatter = new JSONFormatter(giant, 2, { hoverPreviewEnabled: true });
  63. var title = document.createElement('h3');
  64. title.innerText = 'Giant JSON';
  65. result.appendChild(title);
  66. console.time('Rendering giant JSON');
  67. result.appendChild(giantFormatter.render());
  68. console.timeEnd('Rendering giant JSON');
  69. });
  70. })