-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson-sort.html
More file actions
851 lines (791 loc) Β· 46.7 KB
/
Copy pathjson-sort.html
File metadata and controls
851 lines (791 loc) Β· 46.7 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
<!DOCTYPE html>
<html lang="en">
<head>
<include src="_partials/meta-base.html"></include>
<title>JSON Sort β HTML Tools</title>
<meta name="description" content="Sort JSON object keys alphabetically (AβZ or ZβA) recursively, for canonical, line-stable output. Runs in your browser β no installs, no tracking.">
<link rel="canonical" href="https://tools.mazipan.space/json-sort">
<meta property="og:title" content="JSON Sort β HTML Tools">
<meta property="og:description" content="Sort JSON object keys alphabetically (AβZ or ZβA) recursively, for canonical, line-stable output. Runs in your browser β no installs, no tracking.">
<meta property="og:url" content="https://tools.mazipan.space/json-sort">
<meta name="twitter:title" content="JSON Sort β HTML Tools">
<meta name="twitter:description" content="Sort JSON object keys alphabetically (AβZ or ZβA) recursively, for canonical, line-stable output. Runs in your browser β no installs, no tracking.">
<include src="_partials/meta-social.html"></include>
<link rel="icon" type="image/png" sizes="32x32" href="favicon-json-sort.png">
<include src="_partials/head-fonts.html"></include>
<link rel="stylesheet" href="styles.css">
<include src="_partials/head-theme.html"></include>
<!-- BEGIN:json-ld generated by scripts/generate-sections.mjs β re-run after editing tools.json -->
<script type="application/ld+json">{"@context":"https://schema.org","@type":"WebApplication","name":"JSON Sort","url":"https://tools.mazipan.space/json-sort","description":"Sort JSON object keys alphabetically (AβZ or ZβA) recursively, or pick a preset β package.json (npm), tsconfig.json, composer.json β to apply the canonical field order for that file type. Runs in your browser β no installs, no tracking.","applicationCategory":"DeveloperApplication","operatingSystem":"Any","browserRequirements":"Requires JavaScript","offers":{"@type":"Offer","price":"0","priceCurrency":"USD"},"isPartOf":{"@type":"WebSite","name":"HTML Tools","url":"https://tools.mazipan.space/"}}</script>
<script type="application/ld+json">{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"HTML Tools","item":"https://tools.mazipan.space/"},{"@type":"ListItem","position":2,"name":"JSON Sort","item":"https://tools.mazipan.space/json-sort"}]}</script>
<script type="application/ld+json">{"@context":"https://schema.org","@type":"FAQPage","mainEntity":[{"@type":"Question","name":"Will it sort arrays too?","acceptedAnswer":{"@type":"Answer","text":"No. Only object keys are sorted; arrays preserve their original order, since array order is usually meaningful."}},{"@type":"Question","name":"Does the output stay valid JSON?","acceptedAnswer":{"@type":"Answer","text":"Yes. Lenient input quirks like trailing commas or comments are dropped; the output is always strict JSON."}},{"@type":"Question","name":"Why would I sort JSON keys?","acceptedAnswer":{"@type":"Answer","text":"It produces canonical output for line-stable git diffs, repeatable fingerprints, and easier visual comparison of objects with the same shape."}},{"@type":"Question","name":"Is sorting recursive?","acceptedAnswer":{"@type":"Answer","text":"Yes. Every nested object in the tree is sorted in one pass."}},{"@type":"Question","name":"What does the package.json preset do differently?","acceptedAnswer":{"@type":"Answer","text":"It applies the same field order as keithamus/sort-package-json: known keys (name, version, description, β¦, scripts, dependencies, devDependencies, β¦) follow a fixed sequence; scripts are grouped by `:` namespace with pre/post variants kept next to their main script; dependencies blocks are alpha-sorted (locale-aware); the `exports` field puts path keys first and `default` last. Any unknown top-level keys are appended after, with private (leading `_`) keys at the very end."}},{"@type":"Question","name":"How do AβZ / ZβA interact with a preset?","acceptedAnswer":{"@type":"Answer","text":"The preset fixes the order of its known keys. AβZ and ZβA only control how any extra keys you have that aren't part of the preset are sorted at the end."}}]}</script>
<!-- END:json-ld -->
</head>
<body class="bg-gray-950 text-gray-200 min-h-screen flex flex-col">
<!-- Site header -->
<header class="border-b border-gray-800 px-6 py-4">
<nav aria-label="Breadcrumb" class="max-w-[1100px] mx-auto flex items-center gap-3">
<a href="index.html" class="no-underline text-white font-bold text-lg tracking-tight hover:text-blue-400 transition-colors">
HTML Tools
</a>
<span class="text-gray-700">/</span>
<span class="text-gray-400 text-sm flex items-center gap-1.5" aria-current="page">
π€ JSON Sort
</span>
</nav>
</header>
<main class="max-w-[1100px] mx-auto w-full flex-1 py-8 px-6">
<header class="mb-7">
<h1 class="text-3xl font-bold text-white flex items-center gap-3">π€ JSON Sort</h1>
<p class="mt-1.5 text-sm text-gray-500">Sort JSON object keys alphabetically β or apply a preset (package.json, tsconfig.json, composer.json) β recursively, instantly in your browser.</p>
</header>
<!-- Toolbar -->
<div class="flex flex-wrap gap-2 items-center mb-4">
<label class="flex items-center gap-2 text-xs font-semibold text-gray-400 uppercase tracking-wide">
Preset
<select id="preset" onchange="setPreset(this.value)" class="select" style="text-transform:none;letter-spacing:normal">
<option value="none">Alphabetical</option>
<option value="package">package.json (npm)</option>
<option value="tsconfig">tsconfig.json</option>
<option value="composer">composer.json</option>
</select>
</label>
<span id="order-group" style="display:contents">
<span class="w-px h-5 bg-gray-700 mx-1"></span>
<button id="btn-asc" onclick="setOrder('asc')" class="btn btn-active">A β Z</button>
<button id="btn-desc" onclick="setOrder('desc')" class="btn btn-secondary">Z β A</button>
</span>
<div class="w-px h-5 bg-gray-700 mx-1"></div>
<button onclick="loadSample()" class="btn btn-secondary">π₯ Load sample</button>
<button onclick="clearAll()" class="btn btn-danger">ποΈ Clear</button>
</div>
<!-- Panels -->
<div class="grid grid-cols-2 gap-4 max-md:grid-cols-1">
<div>
<div class="flex items-center justify-between mb-2">
<label class="text-xs font-semibold text-gray-500 uppercase tracking-wide">Input</label>
</div>
<textarea id="input"
placeholder="Paste JSON here..."
spellcheck="false"
oninput="onInput()"
class="w-full h-[500px] min-h-[500px] rounded-lg border border-gray-700 bg-gray-900
text-gray-200 font-mono text-[0.8rem] leading-relaxed p-4 resize-y outline-none
focus:border-blue-400 transition-colors"></textarea>
</div>
<div>
<div class="flex items-center justify-between mb-2">
<label class="text-xs font-semibold text-gray-500 uppercase tracking-wide">Output</label>
<div class="flex gap-1 items-center">
<button onclick="copyOutput()" class="btn btn-secondary btn-sm">π Copy</button>
<span class="w-px h-3 bg-gray-700 mx-0.5"></span>
<button id="btn-tree" onclick="setView('tree')" class="btn btn-sm btn-active">π³ Tree</button>
<button id="btn-raw" onclick="setView('raw')" class="btn btn-secondary btn-sm">π Raw</button>
</div>
</div>
<div id="output"
class="w-full h-[500px] min-h-[500px] rounded-lg border border-gray-700 bg-gray-900
font-mono text-[0.8rem] leading-relaxed p-4 overflow-auto resize-y"></div>
</div>
</div>
<div id="status" class="mt-2.5 text-xs text-gray-500 min-h-[18px]"></div>
</main>
<script src="json-utils.js"></script>
<script>
const inputEl = document.getElementById('input');
const outputEl = document.getElementById('output');
const statusEl = document.getElementById('status');
const orderGroupEl = document.getElementById('order-group');
let sortOrder = 'asc';
let currentView = 'tree';
let currentPreset = 'none';
let lastParsed = null;
let lastSorted = '';
// ββ Order toggle βββββββββββββββββββββββββββββββββββββββββββββ
function setOrder(order) {
sortOrder = order;
const ascBtn = document.getElementById('btn-asc');
const descBtn = document.getElementById('btn-desc');
ascBtn.classList.toggle('btn-active', order === 'asc');
ascBtn.classList.toggle('btn-secondary', order !== 'asc');
descBtn.classList.toggle('btn-active', order === 'desc');
descBtn.classList.toggle('btn-secondary', order !== 'desc');
sort();
}
// ββ Preset selector ββββββββββββββββββββββββββββββββββββββββββ
function setPreset(name) {
currentPreset = PRESETS[name] ? name : 'none';
// Non-alphabetical presets fix their own key order β AβZ / ZβA becomes
// irrelevant for the user, so hide it to remove the dead affordance.
orderGroupEl.style.display = currentPreset === 'none' ? 'contents' : 'none';
// Switching presets implies switching file types, so wipe the previous
// paste β the old input is unlikely to make sense under the new preset.
clearAll();
inputEl.focus();
}
// ββ View toggle ββββββββββββββββββββββββββββββββββββββββββββββ
function setView(v) {
currentView = v;
const treeBtn = document.getElementById('btn-tree');
const rawBtn = document.getElementById('btn-raw');
treeBtn.classList.toggle('btn-active', v === 'tree');
treeBtn.classList.toggle('btn-secondary', v !== 'tree');
rawBtn.classList.toggle('btn-active', v === 'raw');
rawBtn.classList.toggle('btn-secondary', v !== 'raw');
renderOutput();
}
function renderOutput() {
if (!lastParsed && lastSorted === '') { outputEl.innerHTML = ''; return; }
if (currentView === 'tree' && lastParsed !== null) {
outputEl.className = outputEl.className.replace(' whitespace-pre', '');
outputEl.innerHTML = '';
const root = document.createElement('div');
root.className = 'tree-root';
const counter = { n: 1 };
root.appendChild(buildTree(lastParsed, null, true, counter));
outputEl.appendChild(root);
} else {
if (!outputEl.className.includes('whitespace-pre')) {
outputEl.className += ' whitespace-pre';
}
outputEl.innerHTML = highlightRaw(lastSorted);
}
}
// ββ Sort βββββββββββββββββββββββββββββββββββββββββββββββββββββ
const cmpAsc = (a, b) => a.localeCompare(b, 'en');
const cmpDesc = (a, b) => b.localeCompare(a, 'en');
function sortAlpha(value, desc) {
if (Array.isArray(value)) return value.map(v => sortAlpha(v, desc));
if (value !== null && typeof value === 'object') {
const keys = Object.keys(value).sort(desc ? cmpDesc : cmpAsc);
const out = {};
for (const k of keys) out[k] = sortAlpha(value[k], desc);
return out;
}
return value;
}
// Sort an object by a fixed key order; unknown keys are appended in alpha
// order. Known sub-keys can supply a custom `over(child, desc)` handler;
// anything without a handler falls back to deep alphabetical sort.
function sortByOrder(value, order, overs, desc) {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return sortAlpha(value, desc);
}
const allKeys = Object.keys(value);
const known = order.filter(k => allKeys.includes(k));
const rest = allKeys.filter(k => !order.includes(k)).sort(desc ? cmpDesc : cmpAsc);
const out = {};
for (const k of [...known, ...rest]) {
const over = overs && overs[k];
out[k] = over ? over(value[k], desc) : sortAlpha(value[k], desc);
}
return out;
}
function sort() {
const raw = inputEl.value.trim();
if (!raw) {
lastParsed = null; lastSorted = '';
outputEl.innerHTML = '';
outputEl.classList.remove('border-red-500');
outputEl.classList.add('border-gray-700');
setStatus('');
return;
}
try {
const { value, fixed } = tolerantParse(raw);
const preset = PRESETS[currentPreset] || PRESETS.none;
lastParsed = preset.apply(value, sortOrder === 'desc');
lastSorted = JSON.stringify(lastParsed, null, 2);
outputEl.classList.remove('border-red-500');
outputEl.classList.add('border-gray-700');
renderOutput();
const suffix = fixed ? ' Β· auto-fixed' : '';
const orderLabel = sortOrder === 'desc' ? 'Z β A' : 'A β Z';
const presetLabel = currentPreset === 'none' ? '' : ` Β· ${preset.label}`;
setStatus(`Sorted ${orderLabel}${presetLabel} Β· ${countKeys(lastParsed)} keys${suffix}`, 'ok');
} catch (e) {
lastParsed = null; lastSorted = '';
outputEl.classList.remove('border-gray-700');
outputEl.classList.add('border-red-500');
outputEl.textContent = e.message;
setStatus(e.message, 'err');
}
}
// ββ Presets ββββββββββββββββββββββββββββββββββββββββββββββββββ
// npm β package.json (mirrors keithamus/sort-package-json defaults)
const PACKAGE_JSON_FIELDS = [
'$schema', 'name', 'displayName', 'version', 'stableVersion', 'private',
'description', 'categories', 'keywords', 'homepage', 'bugs', 'repository',
'funding', 'license', 'qna', 'author', 'maintainers', 'contributors',
'publisher', 'sideEffects', 'type', 'imports', 'exports', 'main', 'svelte',
'umd:main', 'jsdelivr', 'unpkg', 'module', 'source', 'jsnext:main',
'browser', 'react-native', 'types', 'typesVersions', 'typings', 'style',
'example', 'examplestyle', 'assets', 'bin', 'man', 'directories', 'files',
'workspaces', 'binary', 'scripts', 'betterScripts', 'l10n', 'contributes',
'activationEvents', 'husky', 'simple-git-hooks', 'pre-commit', 'commitlint',
'lint-staged', 'nano-staged', 'config', 'nodemonConfig', 'browserify',
'babel', 'browserslist', 'xo', 'prettier', 'eslintConfig', 'eslintIgnore',
'npmpkgjsonlint', 'npmPackageJsonLintConfig', 'npmpackagejsonlint',
'release', 'remarkConfig', 'stylelint', 'ava', 'jest', 'jest-junit',
'jest-stare', 'mocha', 'nyc', 'c8', 'tap', 'oclif', 'resolutions',
'overrides', 'dependencies', 'devDependencies', 'dependenciesMeta',
'peerDependencies', 'peerDependenciesMeta', 'optionalDependencies',
'bundledDependencies', 'bundleDependencies', 'extensionPack',
'extensionDependencies', 'flat', 'packageManager', 'engines',
'engineStrict', 'devEngines', 'volta', 'languageName', 'os', 'cpu',
'preferGlobal', 'publishConfig', 'icon', 'badges', 'galleryBanner',
'preview', 'markdown', 'pnpm'
];
// npm CLI default lifecycle scripts that may have pre/post variants.
const NPM_LIFECYCLE_SCRIPTS = new Set([
'install', 'pack', 'prepare', 'publish', 'restart', 'shrinkwrap',
'start', 'stop', 'test', 'uninstall', 'version'
]);
// Group script names by `:` namespace, then alpha-sort within each group.
function sortScriptNames(keys, prefix = '') {
const groupMap = new Map();
for (const key of keys) {
const rest = prefix ? key.slice(prefix.length + 1) : key;
const idx = rest.indexOf(':');
if (idx > 0) {
const base = key.slice(0, (prefix ? prefix.length + 1 : 0) + idx);
if (!groupMap.has(base)) groupMap.set(base, []);
groupMap.get(base).push(key);
} else {
if (!groupMap.has(key)) groupMap.set(key, []);
groupMap.get(key).push(key);
}
}
return Array.from(groupMap.keys()).sort().flatMap(group => {
const children = groupMap.get(group);
const hasNested = children.length > 1
&& children.some(k => k !== group && k.startsWith(group + ':'));
if (hasNested) {
const direct = children.filter(k => k === group || !k.startsWith(group + ':')).sort();
const nested = children.filter(k => k.startsWith(group + ':'));
return [...direct, ...sortScriptNames(nested, group)];
}
return children.sort();
});
}
function sortScripts(scripts) {
if (!scripts || typeof scripts !== 'object' || Array.isArray(scripts)) return scripts;
const original = Object.keys(scripts);
const prefixable = new Set();
// Strip pre/post prefixes when the bare name is a known lifecycle script
// or another script in this file (so they sort next to their main).
let names = original.map((name) => {
const omitted = name.replace(/^(?:pre|post)/, '');
if (omitted !== name && (NPM_LIFECYCLE_SCRIPTS.has(omitted) || original.includes(omitted))) {
prefixable.add(omitted);
return omitted;
}
return name;
});
names = Array.from(new Set(names));
names = sortScriptNames(names);
names = names.flatMap(k =>
prefixable.has(k)
? [`pre${k}`, k, `post${k}`].filter(n => n in scripts)
: (k in scripts ? [k] : [])
);
const out = {};
const seen = new Set();
for (const k of names) {
if (seen.has(k) || !(k in scripts)) continue;
seen.add(k);
out[k] = scripts[k];
}
return out;
}
// npm convention: dependencies are always asc, locale-aware. Ignore desc.
function sortDeps(obj) {
if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return obj;
const keys = Object.keys(obj).sort(cmpAsc);
const out = {};
for (const k of keys) out[k] = obj[k];
return out;
}
// `exports` field: path keys (starting with `.`) come first in source order;
// condition keys come next alpha-sorted; `default` is always last.
function sortExports(value) {
if (Array.isArray(value)) return value.map(sortExports);
if (!value || typeof value !== 'object') return value;
const keys = Object.keys(value);
const paths = keys.filter(k => k.startsWith('.'));
const cond = keys.filter(k => !k.startsWith('.') && k !== 'default').sort(cmpAsc);
const def = keys.filter(k => k === 'default');
const out = {};
for (const k of [...paths, ...cond, ...def]) out[k] = sortExports(value[k]);
return out;
}
const uniq = (v) => Array.isArray(v) ? Array.from(new Set(v)) : v;
const uniqSort = (v) => Array.isArray(v) && v.every(x => typeof x === 'string')
? Array.from(new Set(v)).sort(cmpAsc) : v;
const mapArray = (fn) => (v) => Array.isArray(v) ? v.map(fn) : fn(v);
const fixedOrder = (order) => (v, desc) => sortByOrder(v, order, null, desc);
const sortURL = fixedOrder(['type', 'url']);
const sortPerson = fixedOrder(['name', 'email', 'url']);
const sortDirs = fixedOrder(['lib', 'bin', 'man', 'doc', 'example', 'test']);
const sortBugs = fixedOrder(['url', 'email']);
const sortVolta = fixedOrder(['node', 'npm', 'yarn']);
const PACKAGE_JSON_OVERS = {
bugs: sortBugs,
repository: sortURL,
funding: sortURL,
license: sortURL,
author: sortPerson,
maintainers: mapArray(sortPerson),
contributors: mapArray(sortPerson),
categories: uniq,
keywords: uniq,
activationEvents: uniq,
files: uniq,
bundledDependencies: uniqSort,
bundleDependencies: uniqSort,
extensionPack: uniqSort,
extensionDependencies: uniqSort,
directories: sortDirs,
scripts: sortScripts,
betterScripts: sortScripts,
resolutions: sortDeps,
overrides: sortDeps,
dependencies: sortDeps,
devDependencies: sortDeps,
peerDependencies: sortDeps,
optionalDependencies: sortDeps,
exports: sortExports,
volta: sortVolta,
};
function applyPackageJson(value, desc) {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return sortAlpha(value, desc);
}
// Private keys (leading `_`) always go at the very end of the object,
// alpha-sorted among themselves, matching sort-package-json.
const allKeys = Object.keys(value);
const known = PACKAGE_JSON_FIELDS.filter(k => allKeys.includes(k));
const unknownPub = allKeys.filter(k => !PACKAGE_JSON_FIELDS.includes(k) && !k.startsWith('_'));
const unknownPriv = allKeys.filter(k => k.startsWith('_'));
unknownPub.sort(desc ? cmpDesc : cmpAsc);
unknownPriv.sort(desc ? cmpDesc : cmpAsc);
const out = {};
for (const k of [...known, ...unknownPub, ...unknownPriv]) {
const over = PACKAGE_JSON_OVERS[k];
out[k] = over ? over(value[k], desc) : sortAlpha(value[k], desc);
}
return out;
}
// tsconfig.json β top-level order; compilerOptions falls through to alpha.
const TSCONFIG_FIELDS = [
'$schema', 'extends', 'compilerOptions', 'include', 'exclude',
'files', 'references', 'ts-node', 'watchOptions', 'typeAcquisition',
'compileOnSave', 'buildOptions'
];
const applyTsconfig = (v, desc) => sortByOrder(v, TSCONFIG_FIELDS, null, desc);
// composer.json β PHP package manifest. Require-like maps are alpha-sorted.
const COMPOSER_FIELDS = [
'name', 'description', 'version', 'type', 'keywords', 'homepage',
'readme', 'time', 'license', 'authors', 'support', 'funding',
'source', 'dist',
'require', 'require-dev', 'conflict', 'replace', 'provide', 'suggest',
'autoload', 'autoload-dev',
'minimum-stability', 'prefer-stable',
'repositories', 'config',
'scripts', 'scripts-descriptions', 'scripts-aliases',
'extra', 'bin', 'archive', 'abandoned', 'non-feature-branches', '_comment'
];
const COMPOSER_OVERS = {
require: sortDeps,
'require-dev': sortDeps,
conflict: sortDeps,
replace: sortDeps,
provide: sortDeps,
suggest: sortDeps,
};
const applyComposer = (v, desc) => sortByOrder(v, COMPOSER_FIELDS, COMPOSER_OVERS, desc);
const PRESETS = {
none: { label: 'Alphabetical', apply: sortAlpha },
package: { label: 'package.json (npm)', apply: applyPackageJson },
tsconfig: { label: 'tsconfig.json', apply: applyTsconfig },
composer: { label: 'composer.json', apply: applyComposer },
};
// ββ Tree builder βββββββββββββββββββββββββββββββββββββββββββββ
function buildTree(value, key, isLast, counter) {
const node = document.createElement('div');
node.className = 'tree-node';
if (value === null || typeof value !== 'object') {
const row = document.createElement('div');
row.className = 'tree-row';
row.innerHTML =
`<span class="line-num">${counter.n++}</span>` +
'<span class="toggle-btn leaf">βΆ</span>' +
(key !== null ? `<span class="json-key">"${escHtml(key)}"</span><span class="json-punct">: </span>` : '') +
primitiveHtml(value) +
(isLast ? '' : '<span class="tree-comma">,</span>');
node.appendChild(row);
return node;
}
const isArray = Array.isArray(value);
const keys = isArray ? value.map((_, i) => i) : Object.keys(value);
const openB = isArray ? '[' : '{';
const closeB = isArray ? ']' : '}';
const previewLabel = isArray
? `${keys.length} item${keys.length !== 1 ? 's' : ''}`
: `${keys.length} key${keys.length !== 1 ? 's' : ''}`;
const headerRow = document.createElement('div');
headerRow.className = 'tree-row';
headerRow.style.cursor = 'pointer';
const toggleBtn = document.createElement('span');
toggleBtn.className = 'toggle-btn';
toggleBtn.textContent = 'βΌ';
const keyHtml = key !== null
? `<span class="json-key">"${escHtml(String(key))}"</span><span class="json-punct">: </span>`
: '';
headerRow.innerHTML =
`<span class="line-num">${counter.n++}</span>` +
keyHtml +
`<span class="json-punct">${openB}</span>` +
`<span class="collapsed-preview" style="display:none"> ${previewLabel} </span>`;
headerRow.insertBefore(toggleBtn, headerRow.children[1]);
node.appendChild(headerRow);
const childrenEl = document.createElement('div');
childrenEl.className = 'tree-children';
keys.forEach((k, i) => {
childrenEl.appendChild(buildTree(value[k], isArray ? null : k, i === keys.length - 1, counter));
});
node.appendChild(childrenEl);
const footerRow = document.createElement('div');
footerRow.className = 'tree-row';
footerRow.innerHTML =
`<span class="line-num">${counter.n++}</span>` +
'<span class="toggle-btn leaf">βΆ</span>' +
`<span class="json-punct">${closeB}</span>` +
(isLast ? '' : '<span class="tree-comma">,</span>');
node.appendChild(footerRow);
const collapsedPreview = headerRow.querySelector('.collapsed-preview');
let collapsed = false;
toggleBtn.addEventListener('click', (e) => {
e.stopPropagation();
collapsed = !collapsed;
toggleBtn.textContent = collapsed ? 'βΆ' : 'βΌ';
childrenEl.style.display = collapsed ? 'none' : '';
footerRow.style.display = collapsed ? 'none' : '';
collapsedPreview.style.display = collapsed ? 'inline' : 'none';
if (collapsed) {
collapsedPreview.textContent = ` ${previewLabel} ${closeB}${isLast ? '' : ','}`;
}
});
headerRow.addEventListener('click', () => toggleBtn.click());
return node;
}
// ββ Raw syntax highlight βββββββββββββββββββββββββββββββββββββ
function highlightRaw(json) {
const highlighted = escHtml(json).replace(
/("(?:\\u[0-9a-fA-F]{4}|\\[^u]|[^\\"])*"(\s*:)?)|(\b(?:true|false|null)\b)|(-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
(m) => {
if (m.endsWith(':')) return `<span class="json-key">${m}</span>`;
if (m.startsWith('"')) return `<span class="json-string">${m}</span>`;
if (m === 'true' || m === 'false') return `<span class="json-bool">${m}</span>`;
if (m === 'null') return `<span class="json-null">${m}</span>`;
return `<span class="json-number">${m}</span>`;
}
);
const lines = highlighted.split('\n');
const pad = String(lines.length).length;
return lines.map((line, i) =>
`<span class="line-num">${String(i + 1).padStart(pad)}</span>${line}`
).join('\n');
}
// ββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββ
function primitiveHtml(v) {
if (v === null) return `<span class="json-null">null</span>`;
if (typeof v === 'boolean') return `<span class="json-bool">${v}</span>`;
if (typeof v === 'number') return `<span class="json-number">${v}</span>`;
return `<span class="json-string">"${escHtml(v)}"</span>`;
}
function escHtml(s) {
return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
function countKeys(obj) {
if (typeof obj !== 'object' || obj === null) return 0;
const keys = Object.keys(obj);
return keys.length + keys.reduce((s, k) => s + countKeys(obj[k]), 0);
}
function setStatus(msg, type = '') {
statusEl.textContent = msg;
statusEl.className = type === 'ok'
? 'mt-2.5 text-xs min-h-[18px] text-green-400'
: type === 'err'
? 'mt-2.5 text-xs min-h-[18px] text-red-400'
: 'mt-2.5 text-xs min-h-[18px] text-gray-500';
}
function copyOutput() {
if (!lastSorted) return;
navigator.clipboard.writeText(lastSorted).then(() => {
setStatus('Copied to clipboard!', 'ok');
setTimeout(() => setStatus(''), 2000);
});
}
function clearAll() {
inputEl.value = '';
lastParsed = null;
lastSorted = '';
outputEl.innerHTML = '';
outputEl.classList.remove('border-red-500', 'whitespace-pre');
outputEl.classList.add('border-gray-700');
setStatus('');
}
// ββ Samples ββββββββββββββββββββββββββββββββββββββββββββββββββ
// Deliberately unsorted so the user can see the effect immediately.
const SAMPLES = {
none: {
"zebra": "stripes",
"apple": "red",
"nested": { "z_last": 1, "a_first": 2, "m_middle": 3 },
"fruit": ["banana", "apple", "cherry"],
"count": 42,
"_meta": { "version": 1 }
},
package: {
"devDependencies": { "vitest": "^1", "biome": "^1.9", "@types/node": "^22" },
"scripts": {
"postbuild": "echo built",
"lint:fix": "biome check --write",
"test": "vitest",
"build": "tsc -p .",
"lint": "biome check",
"pretest": "npm run lint",
"prebuild": "rimraf dist",
"dev": "tsx watch src/index.ts"
},
"name": "my-package",
"main": "./dist/index.cjs",
"_id": "internal-marker",
"exports": {
".": { "default": "./dist/index.cjs", "types": "./dist/index.d.ts", "import": "./dist/index.mjs" },
"./utils": "./dist/utils.js"
},
"dependencies": { "zod": "^3.23", "cmd-ts": "^0.13" },
"version": "1.2.3",
"myCustomConfig": { "foo": "bar" },
"description": "Example package to demo sort-package-json field order",
"engines": { "pnpm": ">=9", "node": ">=20" },
"keywords": ["example", "demo", "example"],
"repository": { "url": "git+https://github.com/user/repo.git", "type": "git" },
"license": "MIT",
"author": { "url": "https://example.com", "name": "Jane Doe", "email": "jane@example.com" }
},
tsconfig: {
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"],
"compilerOptions": {
"target": "ES2022",
"strict": true,
"esModuleInterop": true,
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "./dist",
"declaration": true,
"skipLibCheck": true
},
"extends": "./tsconfig.base.json",
"$schema": "https://json.schemastore.org/tsconfig",
"ts-node": { "transpileOnly": true }
},
composer: {
"require-dev": { "phpunit/phpunit": "^10", "friendsofphp/php-cs-fixer": "^3" },
"autoload": { "psr-4": { "App\\": "src/" } },
"require": { "php": "^8.2", "guzzlehttp/guzzle": "^7", "symfony/console": "^7" },
"name": "vendor/my-php-pkg",
"authors": [{ "email": "jane@example.com", "name": "Jane Doe", "homepage": "https://example.com" }],
"description": "Example PHP package demonstrating composer.json field order",
"license": "MIT",
"type": "library",
"scripts": { "test": "phpunit", "lint": "php-cs-fixer fix" },
"minimum-stability": "stable"
}
};
function loadSample() {
const sample = SAMPLES[currentPreset] || SAMPLES.none;
inputEl.value = JSON.stringify(sample, null, 2);
sort();
inputEl.focus();
}
let debounceTimer;
function onInput() {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(sort, 300);
}
inputEl.focus();
</script>
<section class="max-w-[1100px] mx-auto w-full px-6 py-8 border-t border-gray-800">
<div class="grid gap-6 md:grid-cols-2">
<div>
<h2 class="text-xl font-bold text-white mb-4">About JSON Sort</h2>
<p class="text-gray-400 leading-relaxed">Sort every key in a JSON object alphabetically β AβZ or ZβA β recursively through nested objects. Or pick a preset for a known file shape (<code class="text-gray-300">package.json</code>, <code class="text-gray-300">tsconfig.json</code>, <code class="text-gray-300">composer.json</code>) to apply the canonical field order developers expect for that file. Useful for canonicalizing config files, producing line-stable diffs, or comparing objects whose keys arrived in a different order.</p>
</div>
<div>
<h2 class="text-xl font-bold text-white mb-4">How to use</h2>
<ol class="text-gray-400 leading-relaxed space-y-2 list-decimal list-inside">
<li>Paste your JSON into the input.</li>
<li>Pick a preset, or leave it on Alphabetical.</li>
<li>Choose the sort direction for any extra keys (AβZ or ZβA).</li>
<li>Copy the canonicalized output to your clipboard.</li>
</ol>
</div>
<div>
<h2 class="text-xl font-bold text-white mb-4">Presets</h2>
<ul class="text-gray-400 leading-relaxed space-y-2 list-disc list-inside">
<li><strong class="text-gray-300">Alphabetical</strong> β deep sort by key name; the AβZ / ZβA toggle controls direction.</li>
<li><strong class="text-gray-300">package.json (npm)</strong> β full <a href="https://github.com/keithamus/sort-package-json" rel="noreferrer noopener" target="_blank" class="text-blue-400">sort-package-json</a> field order, script <code class="text-gray-300">:</code>-namespace grouping with <code class="text-gray-300">pre</code>/<code class="text-gray-300">post</code> kept next to their main, alpha-sorted dependency blocks, and <code class="text-gray-300">exports</code> with <code class="text-gray-300">default</code> last.</li>
<li><strong class="text-gray-300">tsconfig.json</strong> β <code class="text-gray-300">$schema</code>, <code class="text-gray-300">extends</code>, <code class="text-gray-300">compilerOptions</code>, <code class="text-gray-300">include</code>, <code class="text-gray-300">exclude</code>, <code class="text-gray-300">files</code>, <code class="text-gray-300">references</code> in canonical order.</li>
<li><strong class="text-gray-300">composer.json</strong> β PHP package manifest layout (<code class="text-gray-300">name</code>, <code class="text-gray-300">require</code>, <code class="text-gray-300">require-dev</code>, <code class="text-gray-300">autoload</code>, β¦) with require-like maps alpha-sorted.</li>
</ul>
</div>
<div>
<h2 class="text-xl font-bold text-white mb-4">Tips</h2>
<ul class="text-gray-400 leading-relaxed space-y-2 list-disc list-inside">
<li>Arrays keep their original order β only object keys are sorted.</li>
<li>Sorting is recursive, so the entire tree is canonicalized in one pass.</li>
<li>With a preset, AβZ / ZβA only controls how any extra keys (not in the preset) are sorted at the end.</li>
<li>The output is strict JSON; trailing commas or comments in the input are dropped.</li>
</ul>
</div>
</div>
</section>
<!-- BEGIN:faq generated by scripts/generate-sections.mjs β re-run after editing tools.json -->
<section class="max-w-[1100px] mx-auto w-full px-6 py-8 border-t border-gray-800">
<h2 class="text-xl font-bold text-white mb-6">FAQ</h2>
<div class="space-y-2">
<details class="disclosure">
<summary>Will it sort arrays too?</summary>
<div class="disclosure-content"><div class="disclosure-body">No. Only object keys are sorted; arrays preserve their original order, since array order is usually meaningful.</div></div>
</details>
<details class="disclosure">
<summary>Does the output stay valid JSON?</summary>
<div class="disclosure-content"><div class="disclosure-body">Yes. Lenient input quirks like trailing commas or comments are dropped; the output is always strict JSON.</div></div>
</details>
<details class="disclosure">
<summary>Why would I sort JSON keys?</summary>
<div class="disclosure-content"><div class="disclosure-body">It produces canonical output for line-stable git diffs, repeatable fingerprints, and easier visual comparison of objects with the same shape.</div></div>
</details>
<details class="disclosure">
<summary>Is sorting recursive?</summary>
<div class="disclosure-content"><div class="disclosure-body">Yes. Every nested object in the tree is sorted in one pass.</div></div>
</details>
<details class="disclosure">
<summary>What does the package.json preset do differently?</summary>
<div class="disclosure-content"><div class="disclosure-body">It applies the same field order as keithamus/sort-package-json: known keys (name, version, description, β¦, scripts, dependencies, devDependencies, β¦) follow a fixed sequence; scripts are grouped by `:` namespace with pre/post variants kept next to their main script; dependencies blocks are alpha-sorted (locale-aware); the `exports` field puts path keys first and `default` last. Any unknown top-level keys are appended after, with private (leading `_`) keys at the very end.</div></div>
</details>
<details class="disclosure">
<summary>How do AβZ / ZβA interact with a preset?</summary>
<div class="disclosure-content"><div class="disclosure-body">The preset fixes the order of its known keys. AβZ and ZβA only control how any extra keys you have that aren't part of the preset are sorted at the end.</div></div>
</details>
</div>
</section>
<!-- END:faq -->
<!-- BEGIN:more-tools generated by scripts/generate-sections.mjs β re-run after editing tools.json -->
<section class="max-w-[1100px] mx-auto w-full px-6 py-8 border-t border-gray-800">
<h2 class="text-xl font-bold text-white mb-6">More tools</h2>
<div class="space-y-4">
<div>
<h3 class="text-xs font-semibold uppercase tracking-wider text-gray-500 mb-2">JSON</h3>
<div class="flex flex-wrap gap-x-5 gap-y-2">
<a href="/json-formatter" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">ποΈ JSON Formatter</a>
<a href="/json-to-ts" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π· JSON to TypeScript</a>
<a href="/json-diff" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π JSON Diff</a>
<a href="/csv-to-json" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π JSON β CSV</a>
<a href="/json-to-yaml" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π JSON β YAML</a>
<a href="/json-to-schema" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π‘οΈ JSON to Validator Schema</a>
</div>
</div>
<div>
<h3 class="text-xs font-semibold uppercase tracking-wider text-gray-500 mb-2">Code</h3>
<div class="flex flex-wrap gap-x-5 gap-y-2">
<a href="/regex-tester" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π§ͺ Regex Tester</a>
<a href="/svg-to-jsx" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">βοΈ SVG to JSX</a>
<a href="/svg-rasterizer" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π· SVG to Raster</a>
<a href="/cron-decoder" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">β±οΈ Cron Decoder</a>
<a href="/snippet-to-image" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">πΈ Code Snippet to Image</a>
<a href="/text-diff" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π Text Diff</a>
<a href="/markdown-preview" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π Markdown Preview</a>
<a href="/semver-checker" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π·οΈ SemVer Checker</a>
<a href="/jwt-decoder" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π JWT Decoder</a>
</div>
</div>
<div>
<h3 class="text-xs font-semibold uppercase tracking-wider text-gray-500 mb-2">Ornaments</h3>
<div class="flex flex-wrap gap-x-5 gap-y-2">
<a href="/gradients" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π¨ Gradients</a>
<a href="/blob" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π«§ Blob Generator</a>
<a href="/waves" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">γ°οΈ Wave Generator</a>
</div>
</div>
<div>
<h3 class="text-xs font-semibold uppercase tracking-wider text-gray-500 mb-2">Image</h3>
<div class="flex flex-wrap gap-x-5 gap-y-2">
<a href="/image-compressor" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">ποΈ Image Compressor</a>
<a href="/image-resizer" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π Image Resizer</a>
<a href="/image-cropper" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">βοΈ Image Cropper</a>
<a href="/image-converter" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">πΌοΈ Image Format Converter</a>
<a href="/image-watermark" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π Image Watermark</a>
</div>
</div>
<div>
<h3 class="text-xs font-semibold uppercase tracking-wider text-gray-500 mb-2">Audio</h3>
<div class="flex flex-wrap gap-x-5 gap-y-2">
<a href="/mp3-tag-editor" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π΅ MP3 Tag Editor</a>
</div>
</div>
<div>
<h3 class="text-xs font-semibold uppercase tracking-wider text-gray-500 mb-2">Web / SEO</h3>
<div class="flex flex-wrap gap-x-5 gap-y-2">
<a href="/meta-tag-preview" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π Meta Tag Preview</a>
<a href="/user-agent-parser" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π΅οΈ User Agent Parser</a>
<a href="/og-image-builder" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">πΌοΈ OG Image Builder</a>
</div>
</div>
<div>
<h3 class="text-xs font-semibold uppercase tracking-wider text-gray-500 mb-2">Generators</h3>
<div class="flex flex-wrap gap-x-5 gap-y-2">
<a href="/qr-code-generator" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π± QR Code Generator</a>
<a href="/lorem-ipsum" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π Lorem Ipsum Generator</a>
<a href="/avatar-generator" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π€ Avatar Generator</a>
<a href="/favicon-generator" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">β Favicon Generator</a>
<a href="/uuid-generator" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">πͺͺ UUID Generator</a>
<a href="/wheel-of-names" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π‘ Wheel of Names</a>
</div>
</div>
<div>
<h3 class="text-xs font-semibold uppercase tracking-wider text-gray-500 mb-2">PDF</h3>
<div class="flex flex-wrap gap-x-5 gap-y-2">
<a href="/pdf-merger" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π PDF Merger</a>
<a href="/image-to-pdf" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π Image to PDF</a>
<a href="/pdf-compressor" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π€ PDF Compressor</a>
<a href="/pdf-splitter" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">βοΈ PDF Splitter</a>
<a href="/pdf-page-manager" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">ποΈ PDF Page Manager</a>
<a href="/pdf-watermark" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π§ PDF Watermark</a>
<a href="/pdf-signature" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">βοΈ PDF Signature</a>
<a href="/pdf-to-image" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">πΌοΈ PDF to Image</a>
</div>
</div>
<div>
<h3 class="text-xs font-semibold uppercase tracking-wider text-gray-500 mb-2">Time</h3>
<div class="flex flex-wrap gap-x-5 gap-y-2">
<a href="/pomodoro-timer" class="text-sm text-gray-300 hover:text-blue-400 transition-colors no-underline">π
Pomodoro Timer</a>
</div>
</div>
</div>
</section>
<!-- END:more-tools -->
<footer class="max-w-[1100px] mx-auto w-full py-8 px-6 border-t border-gray-800 text-center text-sm text-gray-600">
<div>© <span id="year"></span> <a href="https://mazipan.space" rel="noreferrer noopener" target="_blank" class="text-blue-400 transition-colors">Irfan Maulana</a> & Claude</div>
<div><span id="deploy-time"></span></div>
<div><span id="commit-sha"></span><a href="https://github.com/mazipan/html-tools" rel="noreferrer noopener" target="_blank" class="text-blue-400 transition-colors">Source</a></div>
<div><a href="design-system.html" rel="nofollow" class="text-blue-400 transition-colors">Design system</a></div>
<div><a href="https://baca-quran.id" rel="noreferrer noopener" target="_blank" class="text-blue-400 transition-colors">Baca Quran</a> Β· <a href="https://games.mazipan.space" rel="noreferrer noopener" target="_blank" class="text-blue-400 transition-colors">Games</a></div>
</footer>
<include src="_partials/footer-script.html"></include>
</body>
</html>