-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimple_json.go
139 lines (127 loc) · 2.52 KB
/
simple_json.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package requests
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"time"
)
type Value struct {
Data interface{}
Exists bool
}
func NewJson(data []byte) (Value, error) {
v := Value{}
err := json.Unmarshal(data, &v.Data)
if err == nil {
v.Exists = true
} else {
return v, err
}
return v, nil
}
func (v Value) Get(path ...interface{}) Value {
if v.Data == nil || !v.Exists {
return v
}
for _, key := range path {
if v.Data == nil || !v.Exists {
break
}
switch v.Data.(type) {
case map[string]interface{}:
switch key.(type) {
case string:
v.Data = v.Data.(map[string]interface{})[key.(string)]
}
case []interface{}:
varray := v.Data.([]interface{})
switch key.(type) {
case int:
if key.(int) < len(varray) {
v.Data = varray[key.(int)]
} else {
v.Data = nil
}
}
}
}
return v
}
func (v Value) String() string {
if v.Data == nil {
return ""
}
return fmt.Sprintf(`%v`, v.Data)
}
func (v Value) Int64() int64 {
if v.Data == nil || !v.Exists {
return 0
}
i, _ := strconv.ParseInt(strings.ToLower(v.String()), 10, 64)
return i
}
func (v Value) Float64() float64 {
if v.Data == nil || !v.Exists {
return 0
}
f, _ := strconv.ParseFloat(strings.ToLower(v.String()), 64)
return f
}
func (v Value) Bool() bool {
if v.Data == nil || !v.Exists {
return false
}
b, _ := strconv.ParseBool(strings.ToLower(v.String()))
return b
}
func (v Value) Time(layout string, options ...string) time.Time {
if v.Data == nil || !v.Exists {
return time.Now()
}
if len(options) > 0 && options[0] == "utc" {
tm, err := time.ParseInLocation(layout, v.String(), time.UTC)
if err != nil {
return time.Now()
}
return tm.Local()
}
tm, err := time.ParseInLocation(layout, v.String(), time.Local)
if err != nil {
return time.Now()
}
return tm.Local()
}
func (v Value) Size() int {
if v.Data == nil || !v.Exists {
return 0
}
switch v.Data.(type) {
case []interface{}:
return len(v.Data.([]interface{}))
}
return 0
}
func (v Value) Map() map[string]interface{} {
tmpMap := make(map[string]interface{})
if v.Data == nil || !v.Exists {
return tmpMap
}
switch v.Data.(type) {
case map[string]interface{}:
tmpMap = v.Data.(map[string]interface{})
}
return tmpMap
}
func (v Value) StringArray(path ...interface{}) []string {
tmpArray := make([]string, 0, v.Size())
if v.Data == nil || !v.Exists {
return tmpArray
}
if v.Size() > 0 {
for i := 0; i < v.Size(); i++ {
tmpArray = append(tmpArray, v.Get(i).Get(path...).String())
}
}
return tmpArray
}