-
Notifications
You must be signed in to change notification settings - Fork 2
/
walk.go
63 lines (59 loc) · 1.3 KB
/
walk.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
package jin
import "strconv"
func (j *JO) Walk(callback func(k string, v []byte, p []string) (bool, error)) error {
path := []string{}
return walk(j.body, path, callback)
}
func Walk(json []byte, callback func(k string, v []byte, p []string) (bool, error)) error {
path := []string{}
return walk(json, path, callback)
}
func walk(json []byte, path []string, callback func(k string, v []byte, p []string) (bool, error)) error {
t, err := GetType(json, path...)
if err != nil {
return err
}
switch t {
case TypeObject:
err := IterateKeyValue(json, func(keyBytes, _ []byte) (bool, error) {
err = walk(json, append(path, string(keyBytes)), callback)
if err != nil {
return false, err
}
return true, nil
}, path...)
if err != nil {
return err
}
case TypeArray:
i := 0
err := IterateArray(json, func(_ []byte) (bool, error) {
err = walk(json, append(path, strconv.Itoa(i)), callback)
if err != nil {
return false, err
}
i++
return true, nil
}, path...)
if err != nil {
return err
}
default:
key := ""
if len(path) != 0 {
key = path[len(path)-1]
}
val, err := Get(json, path...)
if err != nil {
return err
}
keepGoing, err := callback(key, val, path)
if err != nil {
return err
}
if !keepGoing {
return nil
}
}
return nil
}