-
Notifications
You must be signed in to change notification settings - Fork 0
/
jq_array_parser.go
77 lines (70 loc) · 1.75 KB
/
jq_array_parser.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package opslevel_jq_parser
import (
"encoding/json"
"fmt"
"strings"
libjq_go "github.com/flant/libjq-go"
"github.com/rs/zerolog/log"
)
type JQArrayParser struct {
programs []*JQFieldParser
}
func NewJQArrayParser(expressions []string) *JQArrayParser {
programs := make([]*JQFieldParser, len(expressions))
for i, expression := range expressions {
programs[i] = NewJQFieldParser(expression)
}
return &JQArrayParser{
programs: programs,
}
}
func (p *JQArrayParser) Run(data string) ([]string, error) {
output := make([]string, 0, len(p.programs))
for _, program := range p.programs {
response, err := program.Run(data)
if err != nil {
log.Warn().Err(err).Msgf("jq execution error from expression: %s", program.program.Program)
continue
}
if response == "" {
continue
}
if strings.HasPrefix(response, "[") && strings.HasSuffix(response, "]") {
var aliases []string
if err := json.Unmarshal([]byte(response), &aliases); err == nil {
for _, alias := range aliases {
if alias == "" {
continue
}
output = append(output, alias)
}
}
} else {
output = append(output, response)
}
}
return runJQUnique[string](output)
}
func runJQUnique[T any](inputArray []T, uniqueBy ...string) ([]T, error) {
if len(uniqueBy) == 0 {
uniqueBy = []string{"."}
}
expression := fmt.Sprintf("unique_by(%s)", strings.Join(uniqueBy, ","))
rawJSON, err := json.Marshal(inputArray)
if err != nil {
return nil, err
}
resultArray, err := libjq_go.Jq().Program(expression).RunRaw(string(rawJSON))
if err != nil {
return nil, err
}
if resultArray == "null" {
return nil, nil
}
var uniqueArray []T
err = json.Unmarshal([]byte(resultArray), &uniqueArray)
if err != nil {
return nil, err
}
return uniqueArray, nil
}