forked from xiatechs/jsonata-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
processor.go
65 lines (48 loc) · 1.32 KB
/
processor.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
package jsonata
import (
"fmt"
)
type JsonataProcessor struct {
tree *Expr
}
func NewProcessor(jsonataString string) (j *JsonataProcessor, err error) {
defer func() { // go-jsonata uses panic fallthrough design so this is necessary
if r := recover(); r != nil {
err = fmt.Errorf("jsonata error: %v", r)
}
}()
jsnt := replaceQuotesAndCommentsInPaths(jsonataString)
e := MustCompile(jsnt)
j = &JsonataProcessor{}
j.tree = e
return j, err
}
// Execute - helper function that lets you parse and run jsonata scripts against an object
func (j *JsonataProcessor) Execute(input interface{}) (output []map[string]interface{}, err error) {
defer func() { // go-jsonata uses panic fallthrough design so this is necessary
if r := recover(); r != nil {
err = fmt.Errorf("jsonata error: %v", r)
}
}()
output = make([]map[string]interface{}, 0)
item, err := j.tree.Eval(input)
if err != nil {
return nil, err
}
if aMap, ok := item.(map[string]interface{}); ok {
output = append(output, aMap)
return output, nil
}
if aList, ok := item.([]interface{}); ok {
for index := range aList {
if aMap, ok := aList[index].(map[string]interface{}); ok {
output = append(output, aMap)
}
}
return output, nil
}
if aList, ok := item.([]map[string]interface{}); ok {
return aList, nil
}
return output, nil
}