Skip to content

Commit ea38c2f

Browse files
committed
Added support for array ranges in dotpaths
1 parent dc03600 commit ea38c2f

File tree

2 files changed

+263
-95
lines changed

2 files changed

+263
-95
lines changed

dotpath/dotpath.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,9 @@ func EvalJSON(p string, src []byte) (interface{}, error) {
5151
// returns a value from the dot ath or error
5252
func Eval(p string, data interface{}) (interface{}, error) {
5353
// Parse the dotpath into an array representing map keys or array indexes
54+
if p == "." {
55+
return data, nil
56+
}
5457
keys, err := parse(p)
5558
if err != nil {
5659
return nil, err
@@ -131,6 +134,47 @@ func findInMap(p []string, m map[string]interface{}) (interface{}, error) {
131134
// or an error if element not present.
132135
func findInArray(p []string, a []interface{}) (interface{}, error) {
133136
if len(p) > 0 {
137+
if strings.Contains(p[0], ":") == true {
138+
//FIXME: Need to return array of remaining dot paths
139+
pts := strings.Split(p[0], ":")
140+
if len(pts) != 2 {
141+
return nil, fmt.Errorf("%q is an invalid range", p[0])
142+
}
143+
var (
144+
i, j int
145+
err error
146+
)
147+
if strings.TrimSpace(pts[0]) == "" {
148+
i = 0
149+
} else {
150+
i, err = strconv.Atoi(pts[0])
151+
}
152+
if err != nil {
153+
return nil, fmt.Errorf("error parsing start of range %q, %s", p[0], err)
154+
}
155+
if strings.TrimSpace(pts[1]) == "" {
156+
j = len(a) - 1
157+
} else {
158+
j, err = strconv.Atoi(pts[1])
159+
}
160+
if err != nil {
161+
return nil, fmt.Errorf("error parsing end of range %q, %s", p[0], err)
162+
}
163+
if len(p) > 1 {
164+
fmt.Printf("DEBUG rest of p: %+v, a -> %+v\n", p[1:], a[i:j])
165+
v := []interface{}{}
166+
for _, sVal := range a[i:j] {
167+
if d, err := find(p[1:], sVal); err != nil {
168+
return nil, fmt.Errorf("Can't find %q in %+v", p[1], sVal)
169+
} else {
170+
v = append(v, d)
171+
}
172+
}
173+
fmt.Printf("DEBUG v: %T -> %+v\n", v, v)
174+
return v, nil //fmt.Errorf("range with sub-paths not implemented")
175+
}
176+
return a[i:j], nil
177+
}
134178
i, err := strconv.Atoi(p[0])
135179
if err != nil {
136180
return nil, fmt.Errorf("Can't parse array index %q", p[0])

0 commit comments

Comments
 (0)