Mahesh
Mahesh

Reputation: 8892

Json Marshalling straight to stdout

I am trying to learn Golang and while doing that I wrote below code (part of bigger self learning project) and took the code review from strangers, one of the comment was, "you could have marshalled this straight to stdout, instead of marshalling to heap, then converting to string and then streaming it to stdout"

I have gone through the documentation of encoding/json package and io but not able to piece together the change which is required.

Any pointers or help would be great.

    // Marshal the struct with proper tab indent so it can be readable
    b, err := json.MarshalIndent(res, "", "    ")
    if err != nil {
        log.Fatal(errors.Wrap(err, "error marshaling response data"))
    }

    // Print the output to the stdout
    fmt.Fprint(os.Stdout, string(b))

EDIT

I just found below code sample in documentation:

    var out bytes.Buffer
    json.Indent(&out, b, "=", "\t")
    out.WriteTo(os.Stdout)

But again it writes to heap first before writing to stdout. It does remove one step of converting it to string though.

Upvotes: 3

Views: 2222

Answers (1)

icza
icza

Reputation: 417592

Create and use a json.Encoder directed to os.Stdout. json.NewEncoder() accepts any io.Writer as its destination.

res := map[string]interface{}{
    "one": 1,
    "two": "twotwo",
}

if err := json.NewEncoder(os.Stdout).Encode(res); err != nil {
    panic(err)
}

This will output (directly to Stdout):

{"one":1,"two":"twotwo"}

If you want to set indentation, use its Encoder.SetIndent() method:

enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", "  ")
if err := enc.Encode(res); err != nil {
    panic(err)
}

This will output:

{
  "one": 1,
  "two": "twotwo"
}

Try the examples on the Go Playground.

Upvotes: 8

Related Questions