-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
jsonpath.go
61 lines (50 loc) · 1.32 KB
/
jsonpath.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
package conf
import (
"fmt"
"github.com/tidwall/gjson"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/function"
ctyjson "github.com/zclconf/go-cty/cty/json"
"golang.org/x/xerrors"
)
func getValueAtJSONPath(data, path string) (cty.Value, error) {
result := gjson.Get(data, path)
if !result.Exists() {
return cty.NullVal(cty.String), fmt.Errorf("no value found at jsonpath %q: not found", path)
}
raw := []byte(result.Raw)
ty, err := ctyjson.ImpliedType(raw)
if err != nil {
return cty.DynamicVal, xerrors.Errorf("determining implied type of %s: %w", string(raw), err)
}
return ctyjson.Unmarshal(raw, ty)
}
// JSONPathFunc takes JSON and a query to fetch the value for the query.
var JSONPathFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "data",
Type: cty.String,
},
{
Name: "query",
Type: cty.String,
},
},
VarParam: &function.Parameter{
Name: "file",
Type: cty.String,
},
Type: func(args []cty.Value) (cty.Type, error) {
data := args[0].AsString()
query := args[1].AsString()
v, err := getValueAtJSONPath(data, query)
return v.Type(), err
},
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
data := args[0].AsString()
query := args[1].AsString()
v, err := getValueAtJSONPath(data, query)
return v, err
},
})