forked from Velocidex/velociraptor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson.go
119 lines (98 loc) · 2.32 KB
/
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package utils
import (
"bufio"
"bytes"
"context"
"io"
"github.com/Velocidex/json"
"github.com/Velocidex/ordereddict"
errors "github.com/go-errors/errors"
vjson "www.velocidex.com/golang/velociraptor/json"
)
func ParseJsonToObject(serialized []byte) (*ordereddict.Dict, error) {
if serialized[0] != '{' {
return nil, errors.New("Invalid JSON object")
}
item := ordereddict.NewDict()
err := json.Unmarshal(serialized, &item)
return item, err
}
func ParseJsonToDicts(serialized []byte) ([]*ordereddict.Dict, error) {
if len(serialized) == 0 {
return nil, nil
}
// Support decoding an array of objects.
if serialized[0] == '[' {
var raw_objects []json.RawMessage
err := json.Unmarshal(serialized, &raw_objects)
if err != nil {
return nil, errors.Wrap(err, 0)
}
result := make([]*ordereddict.Dict, 0, len(raw_objects))
for _, raw_message := range raw_objects {
item := ordereddict.NewDict()
err = json.Unmarshal(raw_message, &item)
if err != nil {
return nil, err
}
result = append(result, item)
}
return result, nil
}
// Otherwise, it must be JSONL
lines := bytes.Split(serialized, []byte{'\n'})
result := make([]*ordereddict.Dict, 0, len(lines))
for _, line := range lines {
if len(line) == 0 {
continue
}
item := ordereddict.NewDict()
err := json.Unmarshal(line, &item)
if err != nil {
return nil, err
}
result = append(result, item)
}
return result, nil
}
func DictsToJson(rows []*ordereddict.Dict, opts *json.EncOpts) ([]byte, error) {
out := bytes.Buffer{}
for _, row := range rows {
serialized, err := vjson.MarshalWithOptions(row, opts)
if err != nil {
return nil, err
}
out.Write(serialized)
out.Write([]byte{'\n'})
}
return out.Bytes(), nil
}
func ReadJsonFromFile(ctx context.Context, fd io.Reader) chan *ordereddict.Dict {
output_chan := make(chan *ordereddict.Dict)
go func() {
defer close(output_chan)
reader := bufio.NewReader(fd)
for {
select {
case <-ctx.Done():
return
default:
row_data, err := reader.ReadBytes('\n')
if len(row_data) == 0 || err != nil {
return
}
item := ordereddict.NewDict()
err = item.UnmarshalJSON(row_data)
if err != nil {
continue
}
select {
case <-ctx.Done():
return
case output_chan <- item:
}
}
}
}()
return output_chan
}