forked from digisan/json-tool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasic.go
81 lines (70 loc) · 1.4 KB
/
basic.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package jsontool
import (
"encoding/json"
"strings"
. "github.com/digisan/go-generics"
)
// IsValid :
func IsValid(bytes []byte) bool {
var m any
return json.Unmarshal(bytes, &m) == nil
}
func IsValidStr(str string) bool {
return IsValid([]byte(str))
}
// Minimize :
func Minimize(str string, check bool) string {
failOnErrWhen(check && !IsValidStr(str), "%v", fEf("input string is invalid json string"))
var (
sb = &strings.Builder{}
pc = byte(0)
quotes = false
)
for i := 0; i < len(str); i++ {
c := str[i]
switch {
case c == '"' && pc != '\\':
quotes = !quotes
sb.WriteByte(c)
case !quotes:
if NotIn(c, ' ', '\t', '\n', '\r') {
sb.WriteByte(c)
}
case quotes:
sb.WriteByte(c)
}
pc = c
}
return sb.String()
}
func TryMinimize(str string) string {
if !IsValidStr(str) {
return str
}
return Minimize(str, false)
}
// MarshalRemove :
func MarshalRemove(v any, mFieldOldNew map[string]string, rmFields ...string) (bytes []byte, err error) {
if bytes, err = json.Marshal(v); err != nil {
return nil, err
}
m := make(map[string]any)
json.Unmarshal(bytes, &m)
for _, f := range rmFields {
delete(m, f)
}
NEXT_NEW:
for fOld, fNew := range mFieldOldNew {
for f, v := range m {
if f == fOld {
m[fNew] = v
delete(m, fOld)
continue NEXT_NEW
}
}
}
if bytes, err = json.Marshal(m); err != nil {
return nil, err
}
return bytes, nil
}