-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjson-format.js
61 lines (53 loc) · 1.32 KB
/
json-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
59
60
61
var JsonFormat = (function(){
function format(json){
var indentLevel = 0;
var formattedJson = "";
var quoted = false;
for(var i = 0; i < json.length; i++){
if((json[i] == "{" || json[i] == "[") && !quoted){
formattedJson += json[i] + "\n";
indentLevel++;
formattedJson += indent(indentLevel);
}else if((json[i] == "}" || json[i] == "]") && !quoted){
indentLevel--;
formattedJson += "\n" + indent(indentLevel);
formattedJson += json[i];
}else if(json[i] == ":" && !quoted){
formattedJson += " : ";
}else if(json[i] == "," && !quoted){
formattedJson += ",\n" + indent(indentLevel);
}else if(json[i] == "\"" && !quoted){
quoted = true;
formattedJson += json[i];
}else if(json[i] == "\"" && quoted){
quoted = false;
formattedJson += json[i];
}else{
formattedJson += json[i];
}
}
return formattedJson;
}
function indent(indentLevel){
var indentText = "";
for(var i = 0; i < indentLevel; i++){
indentText += "\t";
}
return indentText;
}
function minify(json){
json = json.replace(/\s*?/gm, "");
json = json.replace(/(\r\n|\n|\r)/gm,"");
json = json.replace(/\t/, "");
return json;
}
function prettify(json){
json = minify(json);
json = format(json);
return json;
}
return {
prettify : prettify,
minify : minify
};
})();