forked from tkeel-io/tdtl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcollectjs_patch.go
93 lines (85 loc) · 2.23 KB
/
collectjs_patch.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 tdtl
import (
"fmt"
"github.com/tkeel-io/tdtl/pkg/json/gjson"
"github.com/tkeel-io/tdtl/pkg/json/jsonparser"
"github.com/tkeel-io/tdtl/pkg/json/sjson"
"strings"
)
func _gjson2JsonNode(ret gjson.Result) Node {
switch ret.Type {
case gjson.True:
return BoolNode(true)
case gjson.False:
return BoolNode(false)
case gjson.Number: // return Float\Int
r := StringNode(ret.Raw)
if strings.Index(r.String(), ".") == -1 {
return r.To(Int)
}
return r.To(Float)
case gjson.String:
return StringNode(ret.Str)
case gjson.JSON:
return JSONNode{
value: []byte(ret.Raw),
datatype: JSON,
}
}
return NULL_RESULT
}
func get(raw []byte, path string) *Collect {
path = path2GJSON(path)
ret := gjson.GetBytes(raw, path)
return New(ret)
}
//
//func Get(raw []byte, path string) []byte {
// //keys := path2JSONPARSER(path)
// //
// //if value, dataType, _, err := jsonparser.Get(raw, keys...); err == nil {
// // return warpValue(dataType, value)
// //} else {
// //
// //}
// path = path2GJSON(path)
// ret := gjson.GetBytes(raw, path)
// ee := gjson.Get(ret.String(), "")
// fmt.Println(ee, ee.Type)
// return []byte(ret.String())
//}
func set(raw []byte, path string, value []byte) ([]byte, error) {
//keys := path2JSONPARSER(path)
//return jsonparser.Set(raw, value, keys...)
return sjson.SetRawBytes(raw, path, value)
}
func add(raw []byte, path string, value []byte) ([]byte, error) {
keys := path2JSONPARSER(path)
return jsonparser.Append(raw, value, keys...)
}
func del(raw []byte, path ...string) []byte {
for _, v := range path {
keys := path2JSONPARSER(v)
raw = jsonparser.Delete(raw, keys...)
}
return raw
}
func forEach(raw []byte, datatype Type, fn func(key []byte, value *Collect)) []byte {
// dispose object.
if datatype == Object {
jsonparser.ObjectEach(raw, func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error {
fn(key, newCollectFromJsonparserResult(dataType, value))
return nil
})
}
// dispose array.
if datatype == Array {
idx := 0
jsonparser.ArrayEach(raw, func(value []byte, dataType jsonparser.ValueType, offset int) error {
fn(Byte(fmt.Sprintf("[%d]", idx)), newCollectFromJsonparserResult(dataType, value))
idx++
return nil
})
}
return raw
}