Skip to content

Commit daadbcd

Browse files
authored
Merge pull request #187 from madnh/feat/script-json-sort
feat: add "Sort JSON" script
2 parents 87ec848 + e564c93 commit daadbcd

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

Scripts/json__sort.js

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
{
3+
"api":1,
4+
"name":"Sort JSON",
5+
"description":"Sort JSON",
6+
"author":"MaDnh",
7+
"icon":"sort-characters",
8+
"tags":"json,sort"
9+
}
10+
**/
11+
12+
function main(state) {
13+
let value = state.text;
14+
15+
try {
16+
value = JSON.parse(value);
17+
} catch (e) {
18+
state.postError("Invalid JSON");
19+
return;
20+
}
21+
22+
value = sort(value);
23+
24+
state.text = JSON.stringify(value, null, 2);
25+
state.postInfo(`Sorted`);
26+
}
27+
28+
29+
function sort(obj) {
30+
if (obj instanceof Array) {
31+
return obj.map(item => sort(item));
32+
}
33+
34+
if (!isPlainObject(obj)) {
35+
return obj
36+
}
37+
38+
const result = {};
39+
const keys = Object.keys(obj);
40+
41+
keys.sort();
42+
keys.forEach(key => {
43+
result[key] = sort(obj[key])
44+
});
45+
46+
return result;
47+
}
48+
49+
function isPlainObject(value) {
50+
return Object.prototype.toString.call(value) === '[object Object]'
51+
}

0 commit comments

Comments
 (0)