Repository navigation
Expand file tree
/
Copy pathjson.go
More file actions
57 lines (46 loc) · 1.35 KB
/
Copy pathjson.go
File metadata and controls
57 lines (46 loc) · 1.35 KB
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
package render
import (
"encoding/json/jsontext"
"encoding/json/v2"
"fmt"
"io"
)
// JSON writes the rows as a flat array of objects holding the given keys in that order. Each row is
// marshaled whole before its keys are picked, so the row's json tags still decide every value and
// every absence. json/v2 marshals a nil slice to [] and escapes no HTML, and MarshalWrite adds no
// trailing newline, so one is appended here.
func JSON[T any](w io.Writer, rows []T, keys []string) error {
object := json.MarshalToFunc(func(enc *jsontext.Encoder, row T) error {
raw, err := json.Marshal(row)
if err != nil {
return err
}
var members map[string]jsontext.Value
if err := json.Unmarshal(raw, &members); err != nil {
return err
}
if err := enc.WriteToken(jsontext.BeginObject); err != nil {
return err
}
for _, k := range keys {
v, ok := members[k]
if !ok {
continue
}
if err := enc.WriteToken(jsontext.String(k)); err != nil {
return err
}
if err := enc.WriteValue(v); err != nil {
return err
}
}
return enc.WriteToken(jsontext.EndObject)
})
if err := json.MarshalWrite(w, rows, json.WithMarshalers(object)); err != nil {
return fmt.Errorf("encoding rows as JSON: %w", err)
}
if _, err := io.WriteString(w, "\n"); err != nil {
return fmt.Errorf("writing the JSON terminator: %w", err)
}
return nil
}