From 3907e0d346adbbc93497034cff4c4cd648c9c8b9 Mon Sep 17 00:00:00 2001 From: baude Date: Mon, 11 Sep 2017 15:51:12 -0500 Subject: [PATCH] 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 --- cmd/kpod/formats/formats.go | 11 +++++++++++ cmd/kpod/ps.go | 4 +++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/cmd/kpod/formats/formats.go b/cmd/kpod/formats/formats.go index 007f09c6..6e5dd242 100644 --- a/cmd/kpod/formats/formats.go +++ b/cmd/kpod/formats/formats.go @@ -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 } diff --git a/cmd/kpod/ps.go b/cmd/kpod/ps.go index 11dcae5e..76bc8b8b 100644 --- a/cmd/kpod/ps.go +++ b/cmd/kpod/ps.go @@ -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 }