-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson-sort.mjs
More file actions
executable file
·34 lines (25 loc) · 934 Bytes
/
Copy pathjson-sort.mjs
File metadata and controls
executable file
·34 lines (25 loc) · 934 Bytes
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
#!/usr/bin/env node
import { argv } from 'node:process';
import { resolve } from 'node:path';
import { readFileSync, writeFileSync, existsSync } from 'node:fs';
import { getType } from '@jagaad/utils';
const files = argv.slice(2);
const jsonFiles = files
.map((file) => resolve(file))
.filter((path) => path.endsWith('.json'))
.filter((path) => existsSync(path));
jsonFiles.forEach((path) => {
console.log('Sorting:', path);
const strings = JSON.parse(readFileSync(path, 'utf8'));
if (!getType(strings, 'object')) return;
const sortedStrings = sortObject(strings);
const content = JSON.stringify(sortedStrings, null, 2);
writeFileSync(path, content);
});
function sortObject(obj) {
const entries = Object.entries(obj);
const sortedEntries = entries
.toSorted(([a], [b]) => a.localeCompare(b))
.map(([k, v]) => (getType(v, 'object') ? [k, sortObject(v)] : [k, v]));
return Object.fromEntries(sortedEntries);
}