How to Go pretty print to a JSON file

5,237 views
Skip to first unread message

nko...@gmail.com

unread,
Feb 21, 2014, 12:43:21 PM2/21/14
to golan...@googlegroups.com

Here's what I do to write a structure to a JSON file -

    type userInputs struct {
     ...
    }

    userInputsJson := userInputs{}
    // Fill  userInputsJson

    fp, err := os.Create(DFLT_INPUT_FILE)
    if err != nil {
        logger.Fatalf("Unable to create %v. Err: %v.", DFLT_INPUT_FILE, err)
        return err
    }
    defer fp.Close()

    encoder := json.NewEncoder(fp)
    if err = encoder.Encode(userInputsJson); err != nil {
        logger.Fatalf("Unable to encode Json file. Err: %v.", err)
        return err
    }

The output is a JSON file that's not very pleasing to the eye. I'd like to have it indented, I looked up online to find MarshalIndent that does it, but I'm not sure how to output that to a file. What am I missing?

Thank you!


C Banning

unread,
Feb 21, 2014, 2:36:49 PM2/21/14
to golan...@googlegroups.com, nko...@gmail.com

nko...@gmail.com

unread,
Feb 21, 2014, 6:10:19 PM2/21/14
to golan...@googlegroups.com, nko...@gmail.com
That worked like a charm. Thank you very much! :)

nko...@gmail.com

unread,
Feb 24, 2014, 1:35:06 PM2/24/14
to golan...@googlegroups.com, nko...@gmail.com
Just wondering if there is way to add comments in the JSON file like right next to the fields.

James Bardin

unread,
Feb 24, 2014, 1:46:48 PM2/24/14
to golan...@googlegroups.com, nko...@gmail.com


On Monday, February 24, 2014 1:35:06 PM UTC-5, nko...@gmail.com wrote:
Just wondering if there is way to add comments in the JSON file like right next to the fields.


Probably not, since comments aren't allowed in JSON. 

Qiang Han

unread,
Feb 25, 2014, 12:37:28 AM2/25/14
to golan...@googlegroups.com, nko...@gmail.com
Why do you use a buffer to read/write, what is the benefit of doing so?

zhouhon...@gmail.com

unread,
May 30, 2018, 8:17:50 PM5/30/18
to golang-nuts
That's awesome. Thanks a lot.

在 2014年2月22日星期六 UTC+13上午8:36:49,C Banning写道:

Rohit Jain

unread,
May 31, 2018, 10:01:36 PM5/31/18
to zhouhon...@gmail.com, golang-nuts
https://github.com/davecgh/go-spew

It's the best 

`spew.Sdump` will basically cover your case
--
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+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


--
Rohit Jain

Dan Kortschak

unread,
Jun 1, 2018, 12:27:22 AM6/1/18
to Rohit Jain, zhouhon...@gmail.com, golang-nuts
Or if you want almost Go syntax output:

https://github.com/kortschak/utter

/plug
Reply all
Reply to author
Forward
0 new messages