-
Notifications
You must be signed in to change notification settings - Fork 0
/
dig.go
68 lines (61 loc) · 1.31 KB
/
dig.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
package arbitrary
// Package arbitrary lets you easily work with unstructured data.
import (
"fmt"
"strconv"
"strings"
)
// Dig into a decoded json object to grab values deep within, without having to
// make all of the intermediate structs.
func Dig(v interface{}, path ...string) (interface{}, error) {
retVal := v
lastVal := v
pathInd := 0
for {
switch vv := retVal.(type) {
case map[string]interface{}:
lastVal = retVal
retVal = vv[path[pathInd]]
pathInd++
case []interface{}:
index, err := cleanArrayInd(path[pathInd])
if err != nil {
return nil, err
}
if len(vv) <= index {
return nil, &digError{
path: path[0 : pathInd+1],
v: vv,
}
}
lastVal = retVal
retVal = vv[index]
pathInd++
default:
return nil, &digError{
path: path[0:pathInd],
v: lastVal,
}
}
if len(path) == pathInd && retVal != nil {
return retVal, nil
}
}
}
func cleanArrayInd(ind string) (int, error) {
return strconv.Atoi(strings.Trim(ind, "[]"))
}
type digError struct {
path []string
v interface{}
}
func (d *digError) Error() string {
pathStr := strings.Join(d.path, ".")
successFullPathStr := strings.Join(d.path[:len(d.path)-1], ".")
return fmt.Sprintf(
"Could not find object at %q.\nFound %#v at %q.",
pathStr,
d.v,
successFullPathStr,
)
}