/
concat.go
71 lines (66 loc) · 1.82 KB
/
concat.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
package transform
import (
"bytes"
"fmt"
"github.com/qntfy/jsonparser"
)
// Concat combines any specified fields and literal strings into a single string value with raw []byte.
func Concat(spec *Config, data []byte) ([]byte, error) {
sourceList, sourceOk := (*spec.Spec)["sources"]
if !sourceOk {
return nil, SpecError("Unable to get sources")
}
targetPath, targetOk := (*spec.Spec)["targetPath"]
if !targetOk {
return nil, SpecError("Unable to get targetPath")
}
delimiter, delimOk := (*spec.Spec)["delim"]
if !delimOk {
// missing delimiter. default to blank
delimiter = ""
}
outString := ""
applyDelim := false
for _, vItem := range sourceList.([]interface{}) {
if applyDelim {
outString += delimiter.(string)
}
value, ok := vItem.(map[string]interface{})["value"]
if !ok {
path, ok := vItem.(map[string]interface{})["path"]
if ok {
zed, err := getJSONRaw(data, path.(string), spec.Require, spec.KeySeparator)
switch {
case err != nil && spec.Require == true:
return nil, RequireError("Path does not exist")
case err != nil:
value = ""
default:
switch zed[0] {
case '[':
temp := ""
jsonparser.ArrayEach(zed, func(value []byte, dataType jsonparser.ValueType, offset int, err error) {
if bytes.Compare(value, []byte("null")) != 0 {
temp += string(value)
}
})
value = temp
case '"':
value = string(zed[1 : len(zed)-1])
default:
value = string(zed)
}
}
} else {
return nil, SpecError(fmt.Sprintf("Error processing %v: must have either value or path specified", vItem))
}
}
outString += value.(string)
applyDelim = true
}
data, err := setJSONRaw(data, bookend([]byte(outString), '"', '"'), targetPath.(string), spec.KeySeparator)
if err != nil {
return nil, err
}
return data, nil
}