Writing Json output to a file

867 views
Skip to first unread message

Mahesh Sharma

unread,
Sep 29, 2022, 1:47:22 PM9/29/22
to golang-nuts
Hi,
I'm collecting some JSON from an end point.  I can print this to screen:
  fmt.Printf("%s\n", bodyText).

I'm struggling to figure how to write the bodyText to a file.

Any help appreciated.





Eli Bendersky

unread,
Sep 29, 2022, 2:03:01 PM9/29/22
to Mahesh Sharma, golang-nuts

In general, for simple usage questions like this one, https://gobyexample.com should be a useful resource

Eli








--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/4e93b717-cc42-4cfa-85ae-daa2a708e914n%40googlegroups.com.

Simon Archer

unread,
Sep 29, 2022, 8:26:21 PM9/29/22
to golang-nuts
import (
    "encoding/json"
    "fmt"
    "io"
)
func PrintPrettyJSON(data any, writer io.Writer) error {
    b, err := json.MarshalIndent(data, "", "    ")
    if err != nil {
        return err
    }
    content := string(b)
    _, err = fmt.Fprintf(writer, "%s\n", content)
    return err
}
Reply all
Reply to author
Forward
0 new messages