-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1069 lines (955 loc) · 39.2 KB
/
script.js
File metadata and controls
1069 lines (955 loc) · 39.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* JSON Viewer Application
* A beautiful, interactive JSON viewer with card view and Excel export
*/
// DOM Elements
const jsonInput = document.getElementById('jsonInput');
const jsonViewer = document.getElementById('jsonViewer');
const errorMessage = document.getElementById('errorMessage');
const statsElement = document.getElementById('stats');
const fileInput = document.getElementById('fileInput');
const formatBtn = document.getElementById('formatBtn');
const clearBtn = document.getElementById('clearBtn');
const copyBtn = document.getElementById('copyBtn');
const expandAllBtn = document.getElementById('expandAllBtn');
const collapseAllBtn = document.getElementById('collapseAllBtn');
const treeViewBtn = document.getElementById('treeViewBtn');
const cardViewBtn = document.getElementById('cardViewBtn');
const exportExcelBtn = document.getElementById('exportExcelBtn');
const exportHtmlBtn = document.getElementById('exportHtmlBtn');
const toast = document.getElementById('toast');
// State
let currentJson = null;
let currentView = 'tree'; // 'tree' or 'card'
let lazyMode = false; // true when last render was from worker (lazy tree)
let pendingCopy = false;
let pendingExportPrep = false;
let pendingExportFormat = 'excel'; // 'excel' | 'html'
// Web Worker for off-thread parse + lazy children
const worker = new Worker('worker.js');
let workerReady = false;
worker.onmessage = (e) => {
const msg = e.data;
if (msg.type === 'ERROR') {
showError(new Error(msg.message));
workerReady = false;
lazyMode = false;
return;
}
if (msg.type === 'READY') {
workerReady = true;
lazyMode = true;
currentJson = null; // full data lives in worker
if (msg.root) {
renderLazyRoot(msg.root);
statsElement.innerHTML = `<span>Root: ${msg.root.kind} ${msg.root.preview}</span>`;
}
return;
}
if (msg.type === 'CHILDREN_RESULT') {
fillLazyChildren(msg.path, msg);
return;
}
if (msg.type === 'RESET_DONE') {
workerReady = false;
lazyMode = false;
return;
}
if (msg.type === 'FORMATTED') {
if (msg.text.length < 500_000) jsonInput.value = msg.text;
else showToast('Formatted (output too large to show in input)');
return;
}
if (msg.type === 'FULL') {
if (pendingCopy) {
pendingCopy = false;
navigator.clipboard.writeText(msg.text).then(() => showToast('Copied to clipboard!')).catch(() => showToast('Failed to copy'));
}
return;
}
if (msg.type === 'EXPORT_DATA') {
pendingExportPrep = false;
exportTableFromWorker(msg, pendingExportFormat);
return;
}
};
function init() {
jsonInput.addEventListener('input', debounce(() => {
if (jsonInput.value.length < 200_000) parseAndRender();
}, 300));
fileInput.addEventListener('change', handleFileUpload);
formatBtn.addEventListener('click', formatInput);
clearBtn.addEventListener('click', clearAll);
copyBtn.addEventListener('click', copyToClipboard);
expandAllBtn.addEventListener('click', expandAll);
collapseAllBtn.addEventListener('click', collapseAll);
treeViewBtn.addEventListener('click', () => switchView('tree'));
cardViewBtn.addEventListener('click', () => switchView('card'));
if (exportExcelBtn) exportExcelBtn.addEventListener('click', () => exportTable('excel'));
if (exportHtmlBtn) exportHtmlBtn.addEventListener('click', () => exportTable('html'));
jsonInput.addEventListener('paste', () => setTimeout(parseAndRender, 0));
}
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => { clearTimeout(timeout); func(...args); };
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
function switchView(view) {
if (lazyMode && view === 'card') {
showToast('Card view is not available for large JSON. Use Tree view.');
return;
}
currentView = view;
treeViewBtn.classList.toggle('active', view === 'tree');
cardViewBtn.classList.toggle('active', view === 'card');
if (currentJson) {
if (view === 'tree') renderJsonTree(currentJson);
else renderCardView(currentJson);
}
}
function parseAndRender() {
const input = jsonInput.value.trim();
errorMessage.classList.remove('visible');
errorMessage.textContent = '';
if (!input) {
showPlaceholder();
statsElement.innerHTML = '';
currentJson = null;
lazyMode = false;
worker.postMessage({ type: 'RESET' });
return;
}
showToast('Parsing in background…');
worker.postMessage({ type: 'LOAD', text: input });
}
function showError(error) {
errorMessage.textContent = `❌ ${error.message}`;
errorMessage.classList.add('visible');
showPlaceholder();
statsElement.innerHTML = '';
}
function showPlaceholder() {
jsonViewer.innerHTML = `<div class="placeholder"><svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line></svg><p>Your formatted JSON will appear here</p></div>`;
}
function updateStats(json) {
const stats = getJsonStats(json);
statsElement.innerHTML = `<span>📦 ${stats.objects} objects</span><span>📋 ${stats.arrays} arrays</span><span>🔑 ${stats.keys} keys</span><span>📝 ${stats.values} values</span>`;
}
function getJsonStats(json, stats = { objects: 0, arrays: 0, keys: 0, values: 0 }) {
if (Array.isArray(json)) { stats.arrays++; json.forEach(item => getJsonStats(item, stats)); }
else if (json !== null && typeof json === 'object') { stats.objects++; const keys = Object.keys(json); stats.keys += keys.length; keys.forEach(key => getJsonStats(json[key], stats)); }
else { stats.values++; }
return stats;
}
// ==================== TREE VIEW ====================
function renderJsonTree(json) {
const tree = document.createElement('ul');
tree.className = 'json-tree';
tree.appendChild(createJsonNode(json, null, false));
jsonViewer.innerHTML = '';
jsonViewer.appendChild(tree);
}
function createJsonNode(value, key, isLast) {
const li = document.createElement('li');
li.className = 'json-item';
const lineDiv = document.createElement('div');
lineDiv.className = 'json-line';
const isObject = value !== null && typeof value === 'object';
const isArray = Array.isArray(value);
if (isObject) {
const toggleBtn = document.createElement('button');
toggleBtn.className = 'json-toggle';
toggleBtn.innerHTML = '▼';
lineDiv.appendChild(toggleBtn);
if (key !== null) {
const keySpan = document.createElement('span');
keySpan.className = 'json-key';
keySpan.textContent = `"${key}"`;
lineDiv.appendChild(keySpan);
const colonSpan = document.createElement('span');
colonSpan.className = 'json-colon';
colonSpan.textContent = ': ';
lineDiv.appendChild(colonSpan);
}
const openBracket = document.createElement('span');
openBracket.className = 'json-bracket open';
openBracket.textContent = isArray ? '[' : '{';
lineDiv.appendChild(openBracket);
const count = isArray ? value.length : Object.keys(value).length;
const countSpan = document.createElement('span');
countSpan.className = 'json-count';
countSpan.textContent = `${count} ${isArray ? 'items' : 'properties'}`;
lineDiv.appendChild(countSpan);
li.appendChild(lineDiv);
const childrenContainer = document.createElement('ul');
childrenContainer.className = 'json-children';
if (isArray) { value.forEach((item, index) => { childrenContainer.appendChild(createJsonNode(item, index, index === value.length - 1)); }); }
else { const keys = Object.keys(value); keys.forEach((k, index) => { childrenContainer.appendChild(createJsonNode(value[k], k, index === keys.length - 1)); }); }
li.appendChild(childrenContainer);
toggleBtn.addEventListener('click', () => {
toggleBtn.classList.toggle('collapsed');
childrenContainer.classList.toggle('collapsed');
});
const closingLine = document.createElement('div');
closingLine.className = 'json-line';
const closeBracket = document.createElement('span');
closeBracket.className = 'json-bracket';
closeBracket.textContent = isArray ? ']' : '}';
closingLine.appendChild(closeBracket);
if (!isLast) { const comma = document.createElement('span'); comma.className = 'json-comma'; comma.textContent = ','; closingLine.appendChild(comma); }
li.appendChild(closingLine);
} else {
const spacer = document.createElement('span');
spacer.style.width = '18px';
spacer.style.display = 'inline-block';
lineDiv.appendChild(spacer);
if (key !== null && typeof key === 'string') {
const keySpan = document.createElement('span');
keySpan.className = 'json-key';
keySpan.textContent = `"${key}"`;
lineDiv.appendChild(keySpan);
const colonSpan = document.createElement('span');
colonSpan.className = 'json-colon';
colonSpan.textContent = ': ';
lineDiv.appendChild(colonSpan);
} else if (key !== null && typeof key === 'number') {
const indexSpan = document.createElement('span');
indexSpan.className = 'json-key';
indexSpan.style.opacity = '0.6';
indexSpan.textContent = `[${key}]`;
lineDiv.appendChild(indexSpan);
const colonSpan = document.createElement('span');
colonSpan.className = 'json-colon';
colonSpan.textContent = ' ';
lineDiv.appendChild(colonSpan);
}
const valueSpan = document.createElement('span');
valueSpan.className = `json-value ${getValueType(value)}`;
valueSpan.textContent = formatValue(value);
lineDiv.appendChild(valueSpan);
if (!isLast) { const comma = document.createElement('span'); comma.className = 'json-comma'; comma.textContent = ','; lineDiv.appendChild(comma); }
li.appendChild(lineDiv);
}
return li;
}
function getValueType(value) {
if (value === null) return 'null';
if (typeof value === 'boolean') return 'boolean';
if (typeof value === 'number') return 'number';
if (typeof value === 'string') return 'string';
return 'unknown';
}
function formatValue(value) {
if (value === null) return 'null';
if (typeof value === 'string') return `"${value}"`;
return String(value);
}
// ==================== LAZY TREE (Worker-based, expand on demand) ====================
function renderLazyRoot(rootInfo) {
jsonViewer.innerHTML = '';
const tree = document.createElement('ul');
tree.className = 'json-tree';
const li = createLazyNode([], null, rootInfo);
tree.appendChild(li);
jsonViewer.appendChild(tree);
}
function createLazyNode(path, key, nodeInfo) {
const li = document.createElement('li');
li.className = 'json-item';
const line = document.createElement('div');
line.className = 'json-line';
const isContainer = nodeInfo.kind === 'array' || nodeInfo.kind === 'object';
if (isContainer) {
const toggleBtn = document.createElement('button');
toggleBtn.className = 'json-toggle';
toggleBtn.textContent = '▶';
line.appendChild(toggleBtn);
if (key !== null) {
const k = document.createElement('span');
k.className = 'json-key';
k.textContent = typeof key === 'number' ? `[${key}]` : `"${key}"`;
line.appendChild(k);
const colon = document.createElement('span');
colon.className = 'json-colon';
colon.textContent = ': ';
line.appendChild(colon);
}
const bracket = document.createElement('span');
bracket.className = 'json-bracket open';
bracket.textContent = nodeInfo.kind === 'array' ? '[' : '{';
line.appendChild(bracket);
const count = document.createElement('span');
count.className = 'json-count';
count.textContent = nodeInfo.preview;
line.appendChild(count);
li.appendChild(line);
const children = document.createElement('ul');
children.className = 'json-children collapsed';
children.dataset.path = JSON.stringify(path);
li.appendChild(children);
let loaded = false;
toggleBtn.addEventListener('click', () => {
const collapsed = children.classList.toggle('collapsed');
toggleBtn.textContent = collapsed ? '▶' : '▼';
if (!collapsed && !loaded) {
loaded = true;
children.innerHTML = '<li class="json-item"><div class="json-line">Loading…</div></li>';
worker.postMessage({ type: 'CHILDREN', path, offset: 0, limit: 200 });
}
});
} else {
const spacer = document.createElement('span');
spacer.style.width = '18px';
spacer.style.display = 'inline-block';
line.appendChild(spacer);
if (key !== null) {
const k = document.createElement('span');
k.className = 'json-key';
k.textContent = typeof key === 'number' ? `[${key}]` : `"${key}"`;
line.appendChild(k);
const colon = document.createElement('span');
colon.className = 'json-colon';
colon.textContent = ': ';
line.appendChild(colon);
}
const v = document.createElement('span');
v.className = `json-value ${nodeInfo.type || 'unknown'}`;
v.textContent = formatValue(nodeInfo.value);
line.appendChild(v);
li.appendChild(line);
}
return li;
}
function fillLazyChildren(path, payload) {
const pathStr = JSON.stringify(path);
const container = document.querySelector(`.json-children[data-path='${CSS.escape(pathStr)}']`);
if (!container) return;
const isAppend = payload.offset > 0;
if (isAppend) {
const loadMoreLi = container.querySelector('li:last-child');
if (loadMoreLi && loadMoreLi.querySelector('.load-more-btn')) loadMoreLi.remove();
} else {
container.innerHTML = '';
}
payload.items.forEach((child) => {
const childPath = [...path, child.key];
container.appendChild(createLazyNode(childPath, child.key, child));
});
if (payload.hasMore) {
const more = document.createElement('button');
more.className = 'btn btn-secondary load-more-btn';
more.textContent = `Load more (${payload.offset + payload.limit} / ${payload.total})`;
more.addEventListener('click', () => {
more.disabled = true;
worker.postMessage({
type: 'CHILDREN',
path,
offset: payload.offset + payload.limit,
limit: 200
});
});
const li = document.createElement('li');
li.className = 'json-item';
const div = document.createElement('div');
div.className = 'json-line';
div.appendChild(more);
li.appendChild(div);
container.appendChild(li);
}
}
// ==================== CARD VIEW ====================
function renderCardView(json) {
jsonViewer.innerHTML = '';
const container = document.createElement('div');
container.className = 'cards-container';
if (Array.isArray(json)) {
// Check if array contains objects with similar structure (for table view)
const hasObjects = json.length > 0 && json.every(item => typeof item === 'object' && item !== null && !Array.isArray(item));
if (hasObjects && json.length > 1) {
// Render as a data table for better readability
container.appendChild(createDataTable(json));
} else {
const grid = document.createElement('div');
grid.className = 'cards-grid';
json.forEach((item, index) => {
if (typeof item === 'object' && item !== null) {
grid.appendChild(createCard(item, `Record ${index + 1}`, 'object', index));
} else {
grid.appendChild(createPrimitiveCard(item, `Item ${index + 1}`));
}
});
container.appendChild(grid);
}
} else if (typeof json === 'object' && json !== null) {
container.appendChild(createDetailCard(json, 'Data Overview'));
} else {
container.appendChild(createPrimitiveCard(json, 'Value'));
}
jsonViewer.appendChild(container);
}
function createDataTable(dataArray) {
const wrapper = document.createElement('div');
wrapper.className = 'data-table-wrapper';
// Get all unique keys from all objects
const allKeys = [...new Set(dataArray.flatMap(obj => Object.keys(obj)))];
// Create table
const table = document.createElement('table');
table.className = 'data-table';
// Header
const thead = document.createElement('thead');
const headerRow = document.createElement('tr');
// Row number header
const thNum = document.createElement('th');
thNum.className = 'row-number-header';
thNum.textContent = '#';
headerRow.appendChild(thNum);
allKeys.forEach(key => {
const th = document.createElement('th');
th.textContent = formatKeyName(key);
th.title = key;
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
table.appendChild(thead);
// Body
const tbody = document.createElement('tbody');
dataArray.forEach((row, index) => {
const tr = document.createElement('tr');
// Row number
const tdNum = document.createElement('td');
tdNum.className = 'row-number';
tdNum.textContent = index + 1;
tr.appendChild(tdNum);
allKeys.forEach(key => {
const td = document.createElement('td');
const value = row[key];
if (value === undefined || value === null) {
td.innerHTML = '<span class="null-value">—</span>';
} else if (typeof value === 'object') {
td.innerHTML = `<span class="object-badge">${Array.isArray(value) ? `[${value.length}]` : '{...}'}</span>`;
td.title = JSON.stringify(value, null, 2);
td.classList.add('has-tooltip');
} else if (typeof value === 'boolean') {
td.innerHTML = `<span class="bool-value ${value}">${value ? '✓' : '✗'}</span>`;
} else if (typeof value === 'number') {
td.innerHTML = `<span class="number-value">${value}</span>`;
} else {
td.textContent = String(value);
if (String(value).length > 30) {
td.title = value;
td.classList.add('truncated');
}
}
tr.appendChild(td);
});
tbody.appendChild(tr);
});
table.appendChild(tbody);
wrapper.appendChild(table);
return wrapper;
}
function formatKeyName(key) {
// Convert snake_case or camelCase to Title Case
return key
.replace(/_/g, ' ')
.replace(/([a-z])([A-Z])/g, '$1 $2')
.replace(/\b\w/g, c => c.toUpperCase());
}
function createDetailCard(obj, title) {
const card = document.createElement('div');
card.className = 'detail-card';
const header = document.createElement('div');
header.className = 'detail-header';
header.innerHTML = `
<div class="detail-title">
<span class="detail-icon">�</span>
<span>${escapeHtml(title)}</span>
</div>
<span class="detail-badge">${Object.keys(obj).length} properties</span>
`;
card.appendChild(header);
const body = document.createElement('div');
body.className = 'detail-body';
// Group properties by type
const groups = { primitives: [], arrays: [], objects: [] };
for (const [key, value] of Object.entries(obj)) {
if (Array.isArray(value)) groups.arrays.push([key, value]);
else if (typeof value === 'object' && value !== null) groups.objects.push([key, value]);
else groups.primitives.push([key, value]);
}
// Render primitives in a nice grid
if (groups.primitives.length > 0) {
const primSection = document.createElement('div');
primSection.className = 'property-grid';
groups.primitives.forEach(([key, value]) => {
primSection.appendChild(createPropertyCard(key, value));
});
body.appendChild(primSection);
}
// Render arrays
groups.arrays.forEach(([key, value]) => {
body.appendChild(createArraySection(key, value));
});
// Render nested objects
groups.objects.forEach(([key, value]) => {
body.appendChild(createObjectSection(key, value));
});
card.appendChild(body);
return card;
}
function createPropertyCard(key, value) {
const prop = document.createElement('div');
prop.className = 'prop-card';
const label = document.createElement('div');
label.className = 'prop-label';
label.textContent = formatKeyName(key);
const val = document.createElement('div');
val.className = `prop-value ${getValueType(value)}${typeof value === 'boolean' ? (value ? ' true' : ' false') : ''}`;
val.textContent = value === null ? 'null' : String(value);
prop.appendChild(label);
prop.appendChild(val);
return prop;
}
function createArraySection(key, arr) {
const section = document.createElement('div');
section.className = 'array-section';
const header = document.createElement('div');
header.className = 'section-header';
header.innerHTML = `
<span class="section-title">📋 ${formatKeyName(key)}</span>
<span class="section-count">${arr.length} items</span>
`;
section.appendChild(header);
const content = document.createElement('div');
content.className = 'section-content';
if (arr.length === 0) {
content.innerHTML = '<span class="empty-msg">Empty array</span>';
} else if (arr.every(v => typeof v !== 'object' || v === null)) {
// Simple array - show as tags
const tags = document.createElement('div');
tags.className = 'tag-list';
arr.forEach(v => {
const tag = document.createElement('span');
tag.className = 'tag';
tag.textContent = v === null ? 'null' : String(v);
tags.appendChild(tag);
});
content.appendChild(tags);
} else {
// Array of objects - show as mini table
content.appendChild(createDataTable(arr.filter(v => typeof v === 'object' && v !== null)));
}
section.appendChild(content);
return section;
}
function createObjectSection(key, obj) {
const section = document.createElement('div');
section.className = 'object-section';
const header = document.createElement('div');
header.className = 'section-header clickable';
header.innerHTML = `
<span class="section-title">📦 ${formatKeyName(key)}</span>
<span class="section-toggle">▼</span>
`;
const content = document.createElement('div');
content.className = 'section-content';
const grid = document.createElement('div');
grid.className = 'property-grid nested';
for (const [k, v] of Object.entries(obj)) {
if (typeof v !== 'object' || v === null) {
grid.appendChild(createPropertyCard(k, v));
}
}
content.appendChild(grid);
header.addEventListener('click', () => {
content.classList.toggle('collapsed');
header.querySelector('.section-toggle').textContent = content.classList.contains('collapsed') ? '▶' : '▼';
});
section.appendChild(header);
section.appendChild(content);
return section;
}
function createCard(obj, title, type, index) {
const card = document.createElement('div');
card.className = 'json-card';
card.style.animationDelay = `${index * 0.05}s`;
const header = document.createElement('div');
header.className = 'card-header';
header.innerHTML = `
<div class="card-title">
<span class="card-index">${index + 1}</span>
<span>${escapeHtml(title)}</span>
</div>
<span class="card-badge">${Object.keys(obj).length} props</span>
`;
card.appendChild(header);
const body = document.createElement('div');
body.className = 'card-body';
// Show only first 6 key properties, rest collapsed
const entries = Object.entries(obj);
const shown = entries.slice(0, 6);
const hidden = entries.slice(6);
shown.forEach(([key, value]) => {
body.appendChild(createPropertyItem(key, value));
});
if (hidden.length > 0) {
const moreBtn = document.createElement('button');
moreBtn.className = 'show-more-btn';
moreBtn.textContent = `+ ${hidden.length} more properties`;
const hiddenContainer = document.createElement('div');
hiddenContainer.className = 'hidden-props collapsed';
hidden.forEach(([key, value]) => {
hiddenContainer.appendChild(createPropertyItem(key, value));
});
moreBtn.addEventListener('click', () => {
hiddenContainer.classList.toggle('collapsed');
moreBtn.textContent = hiddenContainer.classList.contains('collapsed')
? `+ ${hidden.length} more properties`
: '− Show less';
});
body.appendChild(moreBtn);
body.appendChild(hiddenContainer);
}
card.appendChild(body);
return card;
}
function createPropertyItem(key, value) {
const item = document.createElement('div');
item.className = 'property-item';
const label = document.createElement('div');
label.className = 'property-label';
label.textContent = formatKeyName(key);
item.appendChild(label);
if (Array.isArray(value)) {
const badge = document.createElement('span');
badge.className = 'type-badge array';
badge.textContent = `Array [${value.length}]`;
item.appendChild(badge);
} else if (typeof value === 'object' && value !== null) {
const badge = document.createElement('span');
badge.className = 'type-badge object';
badge.textContent = `Object {${Object.keys(value).length}}`;
item.appendChild(badge);
} else {
const valueEl = document.createElement('div');
valueEl.className = `property-value ${getValueType(value)}${typeof value === 'boolean' ? (value ? ' true' : ' false') : ''}`;
valueEl.textContent = value === null ? 'null' : String(value);
item.appendChild(valueEl);
}
return item;
}
function createNestedCard(obj, title) {
const nested = document.createElement('div');
nested.className = 'nested-card';
const header = document.createElement('div');
header.className = 'nested-header';
header.innerHTML = `<span class="nested-title">📦 ${escapeHtml(title)} (${Object.keys(obj).length} props)</span><span class="nested-toggle">▼</span>`;
const body = document.createElement('div');
body.className = 'nested-body';
for (const [key, value] of Object.entries(obj)) {
body.appendChild(createPropertyItem(key, value));
}
header.addEventListener('click', () => {
body.classList.toggle('collapsed');
header.querySelector('.nested-toggle').textContent = body.classList.contains('collapsed') ? '▶' : '▼';
});
nested.appendChild(header);
nested.appendChild(body);
return nested;
}
function createPrimitiveCard(value, title) {
const card = document.createElement('div');
card.className = 'json-card primitive-card';
card.innerHTML = `<div class="primitive-value"><div class="primitive-type">${getValueType(value)}</div><div class="primitive-content ${getValueType(value)}">${escapeHtml(String(value))}</div></div>`;
return card;
}
function escapeHtml(str) {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
const EXPORT_ROW_LIMIT = 50000; // Cap to avoid Excel slowdown; 32k–50k rows usually fine
// ==================== EXPORT (Excel .xls or HTML .html) ====================
function exportTable(format) {
pendingExportFormat = format; // 'excel' | 'html'
if (lazyMode) {
pendingExportPrep = true;
worker.postMessage({ type: 'EXPORT_PREP' });
return;
}
if (!currentJson) {
showToast('No JSON data to export');
return;
}
let data = currentJson;
let sheetName = 'Data';
if (!Array.isArray(data) && typeof data === 'object') {
const keys = Object.keys(data);
const arrayKey = keys.find(k => Array.isArray(data[k]) && data[k].length > 0);
if (arrayKey) {
data = data[arrayKey];
sheetName = arrayKey;
} else {
data = [data];
}
}
if (!Array.isArray(data)) data = [data];
if (data.length === 0) { showToast('No data to export'); return; }
const flatData = data.map(item => flattenObject(item)).slice(0, EXPORT_ROW_LIMIT);
const headers = [...new Set(flatData.flatMap(obj => Object.keys(obj)))];
const html = generateStyledExcelHTML(headers, flatData, sheetName, data.length);
downloadExportBlob(html, format);
if (data.length > EXPORT_ROW_LIMIT) {
showToast(`Exported first ${EXPORT_ROW_LIMIT} of ${data.length} records`);
} else {
showToast(format === 'excel' ? `Exported ${flatData.length} records to Excel!` : `Exported ${flatData.length} records as HTML!`);
}
}
function exportTableFromWorker(msg, format) {
const { sheetName, headers, rows, totalRows } = msg;
if (!rows || rows.length === 0) { showToast('No data to export'); return; }
const html = generateStyledExcelHTML(headers, rows, sheetName, totalRows);
downloadExportBlob(html, format);
if (totalRows > EXPORT_ROW_LIMIT) {
showToast(`Exported first ${EXPORT_ROW_LIMIT} of ${totalRows} records`);
} else {
showToast(format === 'excel' ? `Exported ${rows.length} records to Excel!` : `Exported ${rows.length} records as HTML!`);
}
}
function downloadExportBlob(html, format) {
const date = new Date().toISOString().slice(0, 10);
const isExcel = format === 'excel';
const blob = new Blob([html], { type: isExcel ? 'application/vnd.ms-excel;charset=utf-8' : 'text/html;charset=utf-8' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `json_export_${date}.${isExcel ? 'xls' : 'html'}`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
function generateStyledExcelHTML(headers, data, title, totalRecords) {
const totalStr = totalRecords != null && totalRecords > data.length
? ` (showing first ${data.length} of ${totalRecords})`
: ` - ${data.length} Records`;
return `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
table {
border-collapse: collapse;
font-family: 'Segoe UI', Tahoma, sans-serif;
font-size: 11pt;
}
th {
background-color: #4472C4;
color: #FFFFFF;
font-weight: bold;
text-align: center;
padding: 10px 15px;
border: 1px solid #2F528F;
}
td {
padding: 8px 12px;
border: 1px solid #B4C6E7;
}
tr:nth-child(even) td {
background-color: #D6DCE5;
}
tr:nth-child(odd) td {
background-color: #FFFFFF;
}
tr:hover td {
background-color: #BDD7EE;
}
.number {
text-align: right;
color: #2F528F;
}
.boolean-true {
color: #2E7D32;
font-weight: bold;
}
.boolean-false {
color: #C62828;
font-weight: bold;
}
.null {
color: #9E9E9E;
font-style: italic;
}
.title {
font-size: 14pt;
font-weight: bold;
color: #1F4E79;
padding: 10px 0;
}
</style>
</head>
<body>
<div class="title">${escapeHtmlForExcel(title)}${totalStr}</div>
<table>
<thead>
<tr>
<th>#</th>
${headers.map(h => `<th>${escapeHtmlForExcel(formatKeyName(h))}</th>`).join('')}
</tr>
</thead>
<tbody>
${data.map((row, idx) => `
<tr>
<td style="background-color:#F2F2F2; text-align:center; font-weight:bold;">${idx + 1}</td>
${headers.map(h => {
const val = row[h];
if (val === undefined || val === null) {
return `<td class="null">—</td>`;
} else if (typeof val === 'boolean') {
return `<td class="boolean-${val}">${val ? '✓ Yes' : '✗ No'}</td>`;
} else if (typeof val === 'number') {
return `<td class="number">${val}</td>`;
} else {
return `<td>${escapeHtmlForExcel(String(val))}</td>`;
}
}).join('')}
</tr>
`).join('')}
</tbody>
</table>
</body>
</html>`;
}
function escapeHtmlForExcel(str) {
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
}
// CSV fallback if SheetJS not loaded
function exportToCSV() {
let data = currentJson;
if (!Array.isArray(data) && typeof data === 'object') {
const keys = Object.keys(data);
const arrayKey = keys.find(k => Array.isArray(data[k]) && data[k].length > 0);
if (arrayKey) data = data[arrayKey];
else data = [data];
}
if (!Array.isArray(data)) data = [data];
const flatData = data.map(item => flattenObject(item));
const headers = [...new Set(flatData.flatMap(obj => Object.keys(obj)))];
let csv = '\uFEFF' + headers.map(h => escapeCSV(h)).join(',') + '\n';
flatData.forEach(row => {
csv += headers.map(h => escapeCSV(String(row[h] ?? ''))).join(',') + '\n';
});
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = `json_export_${new Date().toISOString().slice(0, 10)}.csv`;
link.click();
showToast('Exported as CSV (fallback)');
}
function flattenObject(obj, prefix = '') {
const result = {};
for (const [key, value] of Object.entries(obj)) {
const newKey = prefix ? `${prefix}.${key}` : key;
if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
Object.assign(result, flattenObject(value, newKey));
} else if (Array.isArray(value)) {
if (value.every(v => typeof v !== 'object' || v === null)) {
result[newKey] = value.join('; ');
} else {
result[newKey] = `[${value.length} items]`;
}
} else {
result[newKey] = value;
}
}
return result;
}
function escapeCSV(str) {
if (str.includes(',') || str.includes('"') || str.includes('\n')) {
return `"${str.replace(/"/g, '""')}"`;
}
return str;
}
// ==================== UTILITY FUNCTIONS ====================
function expandAll() {
document.querySelectorAll('.json-toggle.collapsed').forEach(t => t.classList.remove('collapsed'));
document.querySelectorAll('.json-children.collapsed').forEach(c => {
c.classList.remove('collapsed');
if (c.dataset.path) {
const toggle = c.closest('.json-item')?.querySelector('.json-toggle');
if (toggle) toggle.textContent = '▼';
}
});
document.querySelectorAll('.nested-body.collapsed').forEach(b => { b.classList.remove('collapsed'); b.previousElementSibling.querySelector('.nested-toggle').textContent = '▼'; });
}