-
Notifications
You must be signed in to change notification settings - Fork 0
/
jq.go
77 lines (64 loc) · 1.21 KB
/
jq.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 gq
// #cgo LDFLAGS: -ljq
// #include "jq.h"
import "C"
import "errors"
type JQ struct {
state *C.struct_jq_state
}
func NewJQ() JQ {
jq := JQ{}
jq.Init()
return jq
}
func (jq *JQ) Init() {
jq.state = C.jq_init()
}
func (jq *JQ) Compile(program string) error {
result := C.jq_compile(jq.state, C.CString(program))
if result == 0 {
return errors.New("failed to compile")
} else {
return nil
}
}
func (jq *JQ) CompileArgs(program string, jv Jv) error {
result := C.jq_compile_args(jq.state, C.CString(program), jv.value())
if result == 0 {
return errors.New("failed to compile")
} else {
return nil
}
}
func (jq *JQ) Start(jv Jv) {
C.jq_start(jq.state, jv.v, 0)
}
func (jq *JQ) Iter() chan Jv {
ch := make(chan Jv)
go func() {
for {
value := C.jq_next(jq.state)
if C.jv_is_valid(value) == 1 {
ch <- NewJv(value)
} else {
close(ch)
break
}
}
}()
return ch
}
func (jq *JQ) Parse(buffer string, program string) (result []Jv, err error) {
if err = jq.Compile(program); err != nil {
return
}
parser := NewJVParser(0)
parser.SetBuffer(buffer)
for jv := range parser.Iter() {
jq.Start(jv)
for v := range jq.Iter() {
result = append(result, v)
}
}
return
}