-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjsonSortedStringify.js
More file actions
35 lines (26 loc) · 831 Bytes
/
Copy pathjsonSortedStringify.js
File metadata and controls
35 lines (26 loc) · 831 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
35
function jsonSortedStringify(o, indent, level) {
indent = indent || 0;
level = level || 0;
function tab(dt) { return " ".repeat((level + (dt || 0)) * indent) };
if (typeof o === "number") {
return `${o}`;
}
if (typeof o === "string") {
return `"${o}"`;
}
if (Array.isArray(o)) {
let s = [];
o.forEach( (value) => {
s.push(`\n${tab(+1)}${jsonSortedStringify(value, indent, level + 1)}`);
});
let tail = s.length ? `\n${tab()}` : ``;
return `[${s.sort().join()}${tail}]`;
} else if (typeof o === "object") {
let s = [];
Object.entries(o).forEach( ([key,value]) => {
s.push(`\n${tab(+1)}"${key}": ${jsonSortedStringify(value, indent, level + 1)}`);
});
let tail = s.length ? `\n${tab()}` : ``;
return `{${s.sort().join()}${tail}}`;
}
}