-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsirius.go
114 lines (103 loc) · 1.91 KB
/
sirius.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
package sirius
import (
"encoding/json"
"fmt"
"io"
"os"
"strconv"
)
// SJson doc ...
type SJson struct {
Buf []byte
node jsonNode
}
// Open doc ...
func Open(name string) (*SJson, error) {
jsonFile, err := os.Open(name)
if err != nil {
return nil, err
}
defer jsonFile.Close()
buffer, err := io.ReadAll(jsonFile)
if err != nil {
return nil, err
}
var node jsonNode
err = json.Unmarshal([]byte(buffer), &node)
if err != nil {
return nil, err
}
sjson := SJson{
Buf: buffer,
node: node,
}
return &sjson, nil
}
// Get doc ..
func (g SJson) Get(key string) interface{} {
return getJSONPathValue(key, g.node)
}
// GetString doc ..
func (g SJson) GetString(key string) string {
v := getJSONPathValue(key, g.node)
str, ok := v.(string)
if !ok {
return ""
}
return str
}
// GetInt doc ..
func (g SJson) GetInt(key string) int {
v := getJSONPathValue(key, g.node)
str := fmt.Sprintf("%v", v)
valueInt, err := strconv.Atoi(str)
if err != nil {
return 0
}
return valueInt
}
// GetInt64 doc ..
func (g SJson) GetInt64(key string) int64 {
v := getJSONPathValue(key, g.node)
str := fmt.Sprintf("%v", v)
valueInt64, err := strconv.ParseInt(str, 10, 64)
if err != nil {
return 0
}
return valueInt64
}
// GetFloat64 doc ..
func (g SJson) GetFloat64(key string) float64 {
v := getJSONPathValue(key, g.node)
valueFloat64, ok := v.(float64)
if !ok {
return 0.0
}
return valueFloat64
}
// GetBool doc ..
func (g SJson) GetBool(key string) bool {
v := getJSONPathValue(key, g.node)
valueBool, ok := v.(bool)
if !ok {
return false
}
return valueBool
}
// GetArrayMaps doc ..
func (g SJson) GetArrayMaps(key string) []map[string]interface{} {
v := getJSONPathValue(key, g.node)
value, ok := v.([]interface{})
if !ok {
return nil
}
var a []map[string]interface{}
for _, m := range value {
nm, ok := m.(map[string]interface{})
if !ok {
return nil
}
a = append(a, nm)
}
return a
}