-
Notifications
You must be signed in to change notification settings - Fork 2
/
jsonpath.go
58 lines (46 loc) · 1.11 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
package mutators
import (
"encoding/json"
"fmt"
"io"
"strings"
"github.com/PaesslerAG/jsonpath"
"github.com/batmac/ccat/pkg/log"
)
// https://goessner.net/articles/JsonPath/
func init() {
singleRegister("jsonpath", jSONPath, withDescription("a jsonpath expression to apply (on $, with all ',' replaced by '|', all ':' replaced by '£')"),
withConfigBuilder(stdConfigStringWithDefault("$")),
withCategory("filter"),
)
}
func jSONPath(w io.WriteCloser, r io.ReadCloser, config any) (int64, error) {
buf, err := io.ReadAll(r) // NOT streamable
if err != nil {
return 0, err
}
var v interface{}
if err := json.Unmarshal(buf, &v); err != nil {
return 0, err
}
jp := config.(string)
if jp[0] == '.' {
jp = "$" + jp
}
// replace all "|" with ","
jp = strings.ReplaceAll(jp, "|", ",")
//
jp = strings.ReplaceAll(jp, "£", ":")
log.Debugf("final jsonpath: %s", jp)
values, err := jsonpath.Get(jp, v)
if err != nil {
return 0, err
}
// Marshal the result back to JSON
buf, err = json.Marshal(values)
if err != nil {
return 0, err
}
fmt.Fprintln(w, string(buf))
return int64(len(buf)), nil
}