-
Notifications
You must be signed in to change notification settings - Fork 507
/
Copy pathjson.go
99 lines (86 loc) · 2.36 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
package vql
import (
"bytes"
"time"
"github.com/Velocidex/json"
"www.velocidex.com/golang/velociraptor/constants"
vjson "www.velocidex.com/golang/velociraptor/json"
"www.velocidex.com/golang/vfilter"
)
func EncOptsFromScope(scope vfilter.Scope) *json.EncOpts {
// Default formatter should be very fast.
cb := func(v interface{}, opts *json.EncOpts) ([]byte, error) {
switch t := v.(type) {
case time.Time:
// Marshal the time in the UTC timezone by default.
return t.UTC().MarshalJSON()
case *time.Time:
return t.UTC().MarshalJSON()
}
return nil, json.EncoderCallbackSkip
}
// If the scope contains a TZ variable, then we will use that
// instead.
location_name, pres := scope.Resolve(constants.TZ)
if pres {
location_str, ok := location_name.(string)
if ok {
// If we can not find the time zone just
// ignore it.
l, err := time.LoadLocation(location_str)
if err == nil {
cb = func(v interface{}, opts *json.EncOpts) ([]byte, error) {
switch t := v.(type) {
case time.Time:
// Marshal the time in the desired timezone.
return t.In(l).MarshalJSON()
case *time.Time:
return t.In(l).MarshalJSON()
}
return nil, json.EncoderCallbackSkip
}
}
}
}
// Override time handling to support scope timezones
return vjson.NewEncOpts().
WithCallback(time.Time{}, cb).
WithCallback(&time.Time{}, cb)
}
// Utilities for encoding json via the vfilter API.
func MarshalJson(scope vfilter.Scope) vfilter.RowEncoder {
opts := EncOptsFromScope(scope)
return func(rows []vfilter.Row) ([]byte, error) {
return json.MarshalWithOptions(rows, opts)
}
}
func MarshalJsonIndent(scope vfilter.Scope) vfilter.RowEncoder {
opts := EncOptsFromScope(scope)
return func(rows []vfilter.Row) ([]byte, error) {
b, err := json.MarshalWithOptions(rows, opts)
if err != nil {
return nil, err
}
var buf bytes.Buffer
err = json.Indent(&buf, b, "", " ")
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
}
func MarshalJsonl(scope vfilter.Scope) vfilter.RowEncoder {
options := EncOptsFromScope(scope)
return func(rows []vfilter.Row) ([]byte, error) {
out := bytes.Buffer{}
for _, row := range rows {
serialized, err := json.MarshalWithOptions(row, options)
if err != nil {
return nil, err
}
out.Write(serialized)
out.Write([]byte("\n"))
}
return out.Bytes(), nil
}
}