diff --git a/.nextchanges/cli/json-output-raw-body.md b/.nextchanges/cli/json-output-raw-body.md new file mode 100644 index 00000000000..9b71f752094 --- /dev/null +++ b/.nextchanges/cli/json-output-raw-body.md @@ -0,0 +1 @@ +* `--output json` now works for commands that return a raw response body when that body is JSON, such as `serving-endpoints get-open-api`, `serving-endpoints http-request` and `fs cat` of a JSON file. It previously failed with `json output not supported`; bodies that aren't JSON still fail with that error. ([#7661](https://github.com/databricks/cli/pull/7661)) diff --git a/libs/cmdio/render.go b/libs/cmdio/render.go index bebb63dee72..4c7fd4cb60a 100644 --- a/libs/cmdio/render.go +++ b/libs/cmdio/render.go @@ -84,6 +84,28 @@ func (r readerRenderer) renderText(_ context.Context, w io.Writer) error { return err } +// renderJson passes a response body through when it is already JSON (for +// example a serving endpoint's OpenAPI schema), so --output json works for +// commands that return a raw body. Other bodies still can't be shown as JSON. +func (r readerRenderer) renderJson(_ context.Context, w writeFlusher) error { + data, err := io.ReadAll(r.reader) + if err != nil { + return err + } + if !json.Valid(data) { + return errors.New("json output not supported") + } + var pretty bytes.Buffer + if err := json.Indent(&pretty, bytes.TrimSpace(data), "", " "); err != nil { + return err + } + pretty.WriteByte('\n') + if _, err := w.Write(pretty.Bytes()); err != nil { + return err + } + return w.Flush() +} + type iteratorRenderer[T any] struct { t listing.Iterator[T] bufferSize int diff --git a/libs/cmdio/render_test.go b/libs/cmdio/render_test.go index dc8eec6dd2d..68d89c74e77 100644 --- a/libs/cmdio/render_test.go +++ b/libs/cmdio/render_test.go @@ -171,6 +171,24 @@ func makeTestCases() []testCase { outputFormat: flags.OutputJSON, errMessage: "json output not supported", }, + { + name: "io.Reader with JSON body", + v: strings.NewReader(`{"openapi":"3.1.0","paths":{"/a":[1,2]}}` + "\n"), + outputFormat: flags.OutputJSON, + expected: "{\n \"openapi\": \"3.1.0\",\n \"paths\": {\n \"/a\": [\n 1,\n 2\n ]\n }\n}\n", + }, + { + name: "io.Reader with JSON body as text is unchanged", + v: strings.NewReader(`{"openapi":"3.1.0"}`), + outputFormat: flags.OutputText, + expected: `{"openapi":"3.1.0"}`, + }, + { + name: "io.Reader with big integers keeps them exact", + v: strings.NewReader(`{"id":9007199254740993}`), + outputFormat: flags.OutputJSON, + expected: "{\n \"id\": 9007199254740993\n}\n", + }, } }