Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .nextchanges/cli/json-output-raw-body.md
Original file line number Diff line number Diff line change
@@ -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))
22 changes: 22 additions & 0 deletions libs/cmdio/render.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 18 additions & 0 deletions libs/cmdio/render_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
},
}
}

Expand Down
Loading