-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjsone.go
More file actions
73 lines (68 loc) · 1.64 KB
/
Copy pathjsone.go
File metadata and controls
73 lines (68 loc) · 1.64 KB
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
package jsone
import (
"fmt"
"strconv"
"strings"
)
// Dive accepts either `map[string]interface{}` or `[]interface{}` as the root object
// and uses a `string` or a `[]interface{}` as the path to the node.
func Dive(node interface{}, path interface{}) (interface{}, error) {
keys, err := breakdownPath(path)
if err != nil {
return nil, err
}
for _, key := range keys {
node, err = read(node, key)
if err != nil {
return nil, err
}
}
return node, nil
}
func read(node interface{}, key interface{}) (interface{}, error) {
switch node.(type) {
case []interface{}:
idx, ok := key.(int)
if !ok {
return nil, fmt.Errorf("Index is not an integer")
}
array := node.([]interface{})
if idx >= len(array) {
return nil, fmt.Errorf("Index out of bound")
} else {
node = array[idx]
}
case map[string]interface{}:
key, ok := key.(string)
if !ok {
return nil, fmt.Errorf("Key is not a string")
}
node = node.(map[string]interface{})[key]
default:
return nil, fmt.Errorf("Node can only be of types map[string]interface{} or []interface{}")
}
if node == nil {
return nil, fmt.Errorf("Couldn't find the node")
}
return node, nil
}
func breakdownPath(path interface{}) ([]interface{}, error) {
var keys []interface{}
switch path.(type) {
case string:
names := strings.Split(path.(string), "/")
keys = make([]interface{}, len(names))
for i, v := range names {
if n, err := strconv.Atoi(v); err == nil {
keys[i] = n
} else {
keys[i] = v
}
}
case []interface{}:
keys = path.([]interface{})
default:
return nil, fmt.Errorf("Path can only be of type string of []interface{}")
}
return keys, nil
}