Output single list of json objects

This commit is contained in:
2026-03-16 02:42:04 +01:00
parent 7f93466645
commit 1c7637fbc3
4 changed files with 49 additions and 33 deletions

View File

@@ -33,6 +33,10 @@ func runTopN(args []string) {
results := fanOutTopN(sf.targets, filter, grp, *n, win)
if sf.jsonOut {
printTopNJSONArray(results)
return
}
for _, r := range results {
if hdr := targetHeader(r.target, r.resp.GetSource(), len(sf.targets)); hdr != "" {
fmt.Println(hdr)
@@ -41,11 +45,7 @@ func runTopN(args []string) {
fmt.Fprintf(os.Stderr, "error from %s: %v\n", r.target, r.err)
continue
}
if sf.jsonOut {
printTopNJSON(r)
} else {
printTopNTable(r)
}
printTopNTable(r)
if len(sf.targets) > 1 {
fmt.Println()
}
@@ -99,7 +99,7 @@ func printTopNTable(r topNResult) {
printTable(os.Stdout, rows)
}
func printTopNJSON(r topNResult) {
func printTopNJSONArray(results []topNResult) {
type entry struct {
Label string `json:"label"`
Count int64 `json:"count"`
@@ -109,14 +109,22 @@ func printTopNJSON(r topNResult) {
Target string `json:"target"`
Entries []entry `json:"entries"`
}
o := out{
Source: r.resp.Source,
Target: r.target,
Entries: make([]entry, len(r.resp.Entries)),
rows := make([]out, 0, len(results))
for _, r := range results {
if r.err != nil {
fmt.Fprintf(os.Stderr, "error from %s: %v\n", r.target, r.err)
continue
}
o := out{
Source: r.resp.Source,
Target: r.target,
Entries: make([]entry, len(r.resp.Entries)),
}
for i, e := range r.resp.Entries {
o.Entries[i] = entry{Label: e.Label, Count: e.Count}
}
rows = append(rows, o)
}
for i, e := range r.resp.Entries {
o.Entries[i] = entry{Label: e.Label, Count: e.Count}
}
b, _ := json.Marshal(o)
b, _ := json.Marshal(rows)
fmt.Println(string(b))
}