Return Valid JSON for empty data

For commands that ask for JSON results, if the input to the Go JSON
marshaller is empty, it will return a byte array with a literal
"null" in it.  If that is the case, we should output [] instead
as at least that is valid JSON and will not break consumers of the
data.

Signed-off-by: baude <bbaude@redhat.com>
This commit is contained in:
baude 2017-09-11 15:51:12 -05:00
parent 3363064622
commit 3907e0d346
2 changed files with 14 additions and 1 deletions

View File

@ -8,6 +8,7 @@ import (
"text/tabwriter"
"text/template"
"bytes"
"github.com/ghodss/yaml"
"github.com/pkg/errors"
)
@ -59,6 +60,16 @@ func (j JSONStructArray) Out() error {
if err != nil {
return err
}
// JSON returns a byte array with a literal null [110 117 108 108] in it
// if it is passed empty data. We used bytes.Compare to see if that is
// the case.
if diff := bytes.Compare(data, []byte("null")); diff == 0 {
data = []byte("[]")
}
// If the we did get NULL back, we should spit out {} which is
// at least valid JSON for the consumer.
fmt.Printf("%s\n", data)
return nil
}

View File

@ -398,7 +398,9 @@ func getJSONOutput(containers []*libkpod.ContainerData, nSpace bool) (psOutput [
func generatePsOutput(containers []*libkpod.ContainerData, server *libkpod.ContainerServer, opts psOptions) error {
containersOutput := getContainers(containers, opts)
if len(containersOutput) == 0 {
// In the case of JSON, we want to continue so we at least pass
// {} --valid JSON-- to the consumer
if len(containersOutput) == 0 && opts.format != formats.JSONString {
return nil
}