forked from housepower/clickhouse_sinker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson.go
128 lines (110 loc) · 2.23 KB
/
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
package parser
import (
"encoding/json"
"github.com/housepower/clickhouse_sinker/model"
)
type Parser interface {
Parse(bs []byte) model.Metric
}
func NewParser(typ string, title []string, delimiter string) Parser {
switch typ {
case "json", "gjson":
return &GjsonParser{}
case "fastjson":
return &FastjsonParser{}
case "csv":
return &CsvParser{title: title, delimiter: delimiter}
case "gjson_extend": //extend gjson that could extract the map
return &GjsonExtendParser{}
default:
return &GjsonParser{}
}
}
// JsonParser is replaced by GjsonParser
type JsonParser struct {
}
func (c *JsonParser) Parse(bs []byte) model.Metric {
v := make(map[string]interface{})
json.Unmarshal(bs, &v)
return &JsonMetric{v}
}
type JsonMetric struct {
mp map[string]interface{}
}
func (c *JsonMetric) Get(key string) interface{} {
return c.mp[key]
}
func (c *JsonMetric) GetString(key string) string {
//判断object
val, _ := c.mp[key]
if val == nil {
return ""
}
switch val.(type) {
case map[string]interface{}:
return GetJsonShortStr(val.(map[string]interface{}))
case string:
return val.(string)
}
return ""
}
func (c *JsonMetric) GetArray(key string, t string) interface{} {
//判断object
val, _ := c.mp[key]
switch t {
case "string":
switch val.(type) {
case []string:
return val.([]string)
default:
return []string{}
}
case "float":
switch val.(type) {
case []float64:
return val.([]float64)
default:
return []float64{}
}
case "int":
switch val.(type) {
case []float64:
results := make([]int64, 0, len(val.([]float64)))
for i := range val.([]float64) {
results = append(results, int64(val.([]float64)[i]))
}
return results
default:
return []int64{}
}
default:
panic("not supported array type " + t)
}
return nil
}
func (c *JsonMetric) GetFloat(key string) float64 {
val, _ := c.mp[key]
if val == nil {
return 0
}
switch val.(type) {
case float64:
return val.(float64)
}
return 0
}
func (c *JsonMetric) GetInt(key string) int64 {
val, _ := c.mp[key]
if val == nil {
return 0
}
switch val.(type) {
case float64:
return int64(val.(float64))
}
return 0
}
func GetJsonShortStr(v interface{}) string {
bs, _ := json.Marshal(v)
return string(bs)
}