/
json.go
53 lines (42 loc) · 975 Bytes
/
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
package output
import (
"bytes"
"encoding/json"
"fmt"
"io"
"github.com/open-policy-agent/opa/tester"
)
// JSON represents an Outputter that outputs
// results in JSON format.
type JSON struct {
Writer io.Writer
}
// NewJSON creates a new JSON with the given writer.
func NewJSON(w io.Writer) *JSON {
jsonOutput := JSON{
Writer: w,
}
return &jsonOutput
}
// Output outputs the results.
func (j *JSON) Output(results []CheckResult) error {
for r := range results {
if results[r].FileName == "-" {
results[r].FileName = ""
}
results[r].Queries = nil
}
b, err := json.Marshal(results)
if err != nil {
return fmt.Errorf("marshal json: %w", err)
}
var out bytes.Buffer
if err := json.Indent(&out, b, "", "\t"); err != nil {
return fmt.Errorf("indent: %w", err)
}
fmt.Fprintln(j.Writer, out.String())
return nil
}
func (j *JSON) Report(_ []*tester.Result, _ string) error {
return fmt.Errorf("report is not supported in JSON output")
}