Skip to content

Commit

Permalink
Flatten results for length=1 array in JSON output mode
Browse files Browse the repository at this point in the history
  • Loading branch information
mtardy committed Apr 21, 2022
1 parent fbbbe02 commit 44a2d06
Showing 1 changed file with 16 additions and 5 deletions.
21 changes: 16 additions & 5 deletions pkg/bucket/bucket.go
Original file line number Diff line number Diff line change
Expand Up @@ -336,26 +336,32 @@ func (r Results) JSON(opts ResultsOpts) (string, error) {
type jsonOutput struct {
Bucket string `json:"bucket"`
Comments []string `json:"comments,omitempty"`
Data []map[string]interface{} `json:"data"`
Results []map[string]interface{} `json:"results,omitempty"`
Result map[string]interface{} `json:"result,omitempty"`
}

m := make([]map[string]interface{}, 0)
dataMap := make([]map[string]interface{}, 0)

if len(r.data) != 0 && len(r.headers) != 0 {
for _, row := range r.data {
rowMap := make(map[string]interface{})
for headerNr, header := range r.headers {
rowMap[header] = row[headerNr]
}
m = append(m, rowMap)
dataMap = append(dataMap, rowMap)
}
}

var b []byte
var err error
// if hide name and comments, directly output an array of results
if (opts.ShowName != nil && !*opts.ShowName) && (opts.ShowComments != nil && !*opts.ShowComments) {
b, err = json.Marshal(m)
if len(dataMap) == 1 {
// flatten it, the result is not iterable
b, err = json.Marshal(dataMap[0])
} else {
b, err = json.Marshal(dataMap)
}
} else {
o := jsonOutput{}
// TODO maybe add omitempty
Expand All @@ -366,7 +372,12 @@ func (r Results) JSON(opts ResultsOpts) (string, error) {
o.Comments = r.comments
}
if opts.ShowData == nil || *opts.ShowData {
o.Data = m
if len(dataMap) == 1 {
// flatten it, the result is not iterable
o.Result = dataMap[0]
} else {
o.Results = dataMap
}
}

b, err = json.Marshal(o)
Expand Down

0 comments on commit 44a2d06

Please sign in to comment.