0
0
Fork 0
deno_monorepo/bin/jsort.ts

28 lines
704 B
TypeScript

function sortJSON<T>(obj: T): T {
if (typeof obj !== "object" || Array.isArray(obj) || obj === null) {
return obj;
}
return Object.fromEntries(
Object.entries(obj as Record<string, unknown>).sort((a, b) =>
a[0].localeCompare(b[0])
).map(([k, v]) => [k, sortJSON(v)]),
) as unknown as T;
}
if (import.meta.main) {
if (Deno.args.length !== 1) {
console.error("Usage: jsort <file>");
Deno.exit(1);
}
const filename = Deno.args[0];
const json_text = Deno.readTextFileSync(filename);
const json = JSON.parse(json_text);
const sorted = sortJSON(json);
const sorted_json_text = JSON.stringify(sorted);
Deno.writeTextFileSync(filename, sorted_json_text);
}