summaryrefslogtreecommitdiff
path: root/coll/jsonpath.go
blob: 78ec5689cab3f94e5447bbc1c5f9a1f14a6ae357 (plain)
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 coll

import (
	"fmt"
	"reflect"

	"k8s.io/client-go/util/jsonpath"
)

// JSONPath -
func JSONPath(p string, in interface{}) (interface{}, error) {
	jp, err := parsePath(p)
	if err != nil {
		return nil, fmt.Errorf("couldn't parse JSONPath %s: %w", p, err)
	}
	results, err := jp.FindResults(in)
	if err != nil {
		return nil, fmt.Errorf("executing JSONPath failed: %w", err)
	}

	var out interface{}
	if len(results) == 1 && len(results[0]) == 1 {
		v := results[0][0]
		out, err = extractResult(v)
		if err != nil {
			return nil, err
		}
	} else {
		a := []interface{}{}
		for _, r := range results {
			for _, v := range r {
				o, err := extractResult(v)
				if err != nil {
					return nil, err
				}
				if o != nil {
					a = append(a, o)
				}
			}
		}
		out = a
	}

	return out, nil
}

func parsePath(p string) (*jsonpath.JSONPath, error) {
	jp := jsonpath.New("<jsonpath>")
	err := jp.Parse("{" + p + "}")
	if err != nil {
		return nil, err
	}
	jp.AllowMissingKeys(false)
	return jp, nil
}

func extractResult(v reflect.Value) (interface{}, error) {
	if v.CanInterface() {
		return v.Interface(), nil
	}

	return nil, fmt.Errorf("JSONPath couldn't access field")
}