From 59da40e05cc9bad6229eb4ee4b2c5dbd78862ef7 Mon Sep 17 00:00:00 2001 From: zloglevel Date: Sun, 30 Aug 2026 02:21:42 +0800 Subject: [PATCH] fix(formatter): handle nil JSON values Signed-off-by: zloglevel --- cmd/formatter/formatter.go | 4 ++-- cmd/formatter/formatter_test.go | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/cmd/formatter/formatter.go b/cmd/formatter/formatter.go index 6af92c478db..3450acb9981 100644 --- a/cmd/formatter/formatter.go +++ b/cmd/formatter/formatter.go @@ -31,7 +31,7 @@ func Print(toJSON any, format string, outWriter io.Writer, writerFn func(w io.Wr case TABLE, PRETTY, "": return PrintPrettySection(outWriter, writerFn, headers...) case TemplateLegacyJSON: - switch reflect.TypeOf(toJSON).Kind() { + switch reflect.ValueOf(toJSON).Kind() { case reflect.Slice: s := reflect.ValueOf(toJSON) for i := 0; i < s.Len(); i++ { @@ -50,7 +50,7 @@ func Print(toJSON any, format string, outWriter io.Writer, writerFn func(w io.Wr _, _ = fmt.Fprintln(outWriter, outJSON) } case JSON: - switch reflect.TypeOf(toJSON).Kind() { + switch reflect.ValueOf(toJSON).Kind() { case reflect.Slice: outJSON, err := ToJSON(toJSON, "", "") if err != nil { diff --git a/cmd/formatter/formatter_test.go b/cmd/formatter/formatter_test.go index 07b152559c1..046d4560093 100644 --- a/cmd/formatter/formatter_test.go +++ b/cmd/formatter/formatter_test.go @@ -73,6 +73,16 @@ func TestPrint(t *testing.T) { `) } +func TestPrintNilAsJSON(t *testing.T) { + for _, format := range []string{JSON, TemplateLegacyJSON} { + t.Run(format, func(t *testing.T) { + var output bytes.Buffer + assert.NilError(t, Print(nil, format, &output, func(io.Writer) {})) + assert.Equal(t, output.String(), "null\n") + }) + } +} + func TestColorsGoroutinesLeak(t *testing.T) { goleak.VerifyNone(t) }