-
Notifications
You must be signed in to change notification settings - Fork 66
/
json.go
93 lines (71 loc) · 1.98 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
package queryUtils
import (
"encoding/json"
"fmt"
"github.com/aaronchen2k/deeptest/internal/pkg/consts"
commUtils "github.com/aaronchen2k/deeptest/internal/pkg/utils"
"github.com/antchfx/jsonquery"
"github.com/antchfx/xpath"
"github.com/oliveagle/jsonpath"
"strings"
)
func JsonPath(content string, expression string) (result interface{}, resultType consts.ExtractorResultType, err error) {
if content == "" || expression == "" {
result = consts.ExtractorErr
return
}
content = strings.ReplaceAll(content, "\x00", "")
var jsonData interface{}
err = json.Unmarshal([]byte(content), &jsonData)
if err != nil {
result = consts.ExtractorErr
return
}
obj, err := jsonpath.JsonPathLookup(jsonData, expression)
if err != nil || obj == nil {
result = consts.ExtractorErr
return
}
result, resultType = commUtils.ConvertValueForPersistence(obj)
return
}
func JsonQuery(content string, expression string) (result interface{}, resultType consts.ExtractorResultType) {
doc, err := jsonquery.Parse(strings.NewReader(content))
if err != nil {
result = consts.ContentErr
return
}
if isEvaluate(expression) {
expr, _ := xpath.Compile(expression)
float := expr.Evaluate(jsonquery.CreateXPathNavigator(doc))
result = fmt.Sprintf("%v", float)
return
}
elem, err := jsonquery.Query(doc, expression)
if err != nil || elem == nil {
result = consts.ExtractorErr
return
}
obj := elem.Value()
result, resultType = commUtils.ConvertValueForPersistence(obj)
return
}
func JsonQueryWithType(content string, expression string) (result interface{}) {
doc, err := jsonquery.Parse(strings.NewReader(content))
if err != nil {
result = consts.ContentErr
return
}
elem, err := jsonquery.Query(doc, expression)
if err != nil || elem == nil {
result = consts.ExtractorErr
return
}
result = elem.Value()
//isFloat64 := fmt.Sprintf("%T", result) == "float64"
return
}
func isEvaluate(expression string) (ret bool) {
ret = strings.Index(expression, "count") == 0
return
}