forked from digisan/json-tool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
trim.go
57 lines (51 loc) · 1.26 KB
/
trim.go
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
package jsontool
import (
"log"
"regexp"
)
// js need to be formatted
func TrimFields(js string, rmNull, rmEmptyStr, rmEmptyObj, rmEmptyArr bool) string {
rNull := regexp.MustCompile(`[,{](\n)(\s)+"[^"]+":(\s)+null[,\n]`)
rEmptyStr := regexp.MustCompile(`[,{](\n)(\s)+"[^"]+":(\s)+""[,\n]`)
rEmptyObj := regexp.MustCompile(`[,{](\n)(\s)+"[^"]+":(\s)+\{[\n\s]*\}[,\n]`)
rEmptyArr := regexp.MustCompile(`[,{](\n)(\s)+"[^"]+":(\s)+\[[\n\s]*\][,\n]`)
rTrim := []*regexp.Regexp{}
if rmNull {
rTrim = append(rTrim, rNull)
}
if rmEmptyStr {
rTrim = append(rTrim, rEmptyStr)
}
if rmEmptyObj {
rTrim = append(rTrim, rEmptyObj)
}
if rmEmptyArr {
rTrim = append(rTrim, rEmptyArr)
}
trimmed := js
for _, re := range rTrim {
AGAIN:
rm := false
trimmed = re.ReplaceAllStringFunc(trimmed, func(s string) string {
rm = true
first, last := s[0], s[len(s)-1]
switch {
case first == '{' && last == ',': // first, NOT single
return "{"
case first == '{' && last == '\n': // first, single
return "{"
case first == ',' && last == ',': // NOT first, NOT last
return ","
case first == ',' && last == '\n': // NOT first, the last
return "\n"
default:
log.Fatalln(s)
}
return ""
})
if rm {
goto AGAIN
}
}
return trimmed
}