-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathread_json.go
86 lines (75 loc) · 1.85 KB
/
read_json.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
78
79
80
81
82
83
84
85
86
package main
import (
"bufio"
"fmt"
"io"
"strings"
"github.com/buger/jsonparser"
)
type BroJSONReader struct {
r *bufio.Reader
}
type JSONRecord struct {
line []byte
err error
}
func (r *JSONRecord) String() string {
return strings.Trim(string(r.line), "\n")
}
func (r *JSONRecord) GetString(field string) string {
val, err := jsonparser.GetString(r.line, field)
r.err = err
return val
}
func (r *JSONRecord) GetStringList(field string) []string {
var strings []string
jsonparser.ArrayEach(r.line, func(value []byte, dataType jsonparser.ValueType, offset int, err error) {
strings = append(strings, string(value))
r.err = err
}, field)
return strings
}
func (r *JSONRecord) GetFloat(field string) float64 {
val, err := jsonparser.GetFloat(r.line, field)
r.err = err
return val
}
func (r *JSONRecord) IsMissingFieldError() bool {
return r.err == jsonparser.KeyPathNotFoundError
}
func (r *JSONRecord) Error() error {
if r.err != nil {
return fmt.Errorf("Error parsing %s: %w", r, r.err)
}
return nil
}
func NewBroJSONReader(r *bufio.Reader) *BroJSONReader {
return &BroJSONReader{r: r}
}
func (b *BroJSONReader) Next() (Record, error) {
line, err := b.r.ReadBytes('\n')
if err == io.EOF {
return nil, nil
}
if err != nil {
return nil, err
}
rec := JSONRecord{
line: line,
}
return &rec, nil
}
//GetTimestamp tries to get a field that may be a String or a float64
//Yes, this is terrible, but supporting both timestamps and iso8601 at the same
//time is tricky
//TODO: use a struct type that is a string or float and can be lazy evaluated
//for sorting and for final representation when being upserted
func (r *JSONRecord) GetTimestamp(field string) string {
val, err := jsonparser.GetString(r.line, field)
if err == nil {
return val
}
fval, err := jsonparser.GetFloat(r.line, field)
r.err = err
return fmt.Sprintf("%f", fval)
}