-
Notifications
You must be signed in to change notification settings - Fork 0
/
format.js
58 lines (51 loc) · 1.19 KB
/
format.js
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
var p = [],
push = function(m) {
return '\\' + p.push(m) + '\\';
},
pop = function(m, i) {
return p[i - 1]
},
tabs = function(count) {
return new Array(count + 1).join('\t');
};
var JSONFormat = function(json) {
p = [];
var out = "",
indent = 0;
// Extract backslashes and strings
json = json
.replace(/\\./g, push)
.replace(/(".*?"|'.*?')/g, push)
.replace(/\s+/, '');
// Indent and insert newlines
for (var i = 0; i < json.length; i++) {
var c = json.charAt(i);
switch (c) {
case '{':
case '[':
out += c + "\n" + tabs(++indent);
break;
case '}':
case ']':
out += "\n" + tabs(--indent) + c;
break;
case ',':
out += ",\n" + tabs(indent);
break;
case ':':
out += ": ";
break;
default:
out += c;
break;
}
}
out = out
.replace(/\[[\d,\s]+?\]/g, function(m) {
return m.replace(/\s/g, '');
})
.replace(/\\(\d+)\\/g, pop) // strings
.replace(/\\(\d+)\\/g, pop); // backslashes in strings
return out;
};
module.exports = JSONFormat;