Skip to content

Commit

Permalink
Merge pull request #101 from cli/jq-empty-array
Browse files Browse the repository at this point in the history
Fix printing empty arrays as result of jq expressions
  • Loading branch information
mislav authored Feb 10, 2023
2 parents 11fe5ed + 60896a3 commit 98bbeb2
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 9 deletions.
15 changes: 6 additions & 9 deletions pkg/jq/jq.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ func Evaluate(input io.Reader, output io.Writer, expr string) error {
return err
}

enc := json.NewEncoder(output)

iter := code.Run(responseData)
for {
v, ok := iter.Next()
Expand All @@ -53,18 +55,13 @@ func Evaluate(input io.Reader, output io.Writer, expr string) error {
if err != nil {
return err
}
} else {
var jsonFragment []byte
jsonFragment, err = json.Marshal(v)
} else if tt, ok := v.([]interface{}); ok && tt == nil {
_, err = fmt.Fprint(output, "[]\n")
if err != nil {
return err
}
_, err = output.Write(jsonFragment)
if err != nil {
return err
}
_, err = fmt.Fprint(output, "\n")
if err != nil {
} else {
if err = enc.Encode(v); err != nil {
return err
}
}
Expand Down
16 changes: 16 additions & 0 deletions pkg/jq/jq_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,22 @@ func TestEvaluate(t *testing.T) {
},
wantW: "{\"login\":\"monalisa\"}\n",
},
{
name: "empty array",
args: args{
json: strings.NewReader(`[]`),
expr: `.`,
},
wantW: "[]\n",
},
{
name: "empty array 2",
args: args{
json: strings.NewReader(`[]`),
expr: `[]`,
},
wantW: "[]\n",
},
{
name: "complex",
args: args{
Expand Down

0 comments on commit 98bbeb2

Please sign in to comment.