pretty print a golang string containg a json string

1,831 views
Skip to first unread message

Sankar

unread,
Apr 21, 2015, 4:21:36 AM4/21/15
to golan...@googlegroups.com
Hi,

I have a multi-line go string, say:

s := `{"menu": {
"id": "file","value": "File",
"popup": {
"menuitem": [{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
   ]}}}

Now if I want to pretty print this string such that I can see the beautifully indented JSON string, what is the way to do it ?

Thanks.

Sankar
http://psankar.blogspot.in 

Sankar

unread,
Apr 21, 2015, 4:24:02 AM4/21/15
to golan...@googlegroups.com
The source code is at: http://play.golang.org/p/biXahO--Wx 

if the mail encoding is broken in some mail clients. Thanks.

Péter Szilágyi

unread,
Apr 21, 2015, 5:29:02 AM4/21/15
to Sankar, golang-nuts

--
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.
For more options, visit https://groups.google.com/d/optout.

Sankar P

unread,
Apr 21, 2015, 5:40:00 AM4/21/15
to Péter Szilágyi, golang-nuts
I swear that this is exactly what I have tried but it did not work
then. Now your example code works fine, but when I try to copy the
implementation to work on my code, where the input S is the result of
a customObject.String() method, it is still failing (nothing is
printed), even though printing 'S' prints a long, unformatted, valid
JSON string.

I believe that there is some issue with my code where I am calling
this functionality. I will try to debug it. Thank you for your code :)
--
Sankar P
http://psankar.blogspot.com

Sankar P

unread,
Apr 21, 2015, 5:42:11 AM4/21/15
to Péter Szilágyi, golang-nuts
Got it. You made me debug and the problem was right in front of my
eyes. My string had an embedded "\b" (aimed at console printing) and
that was the cause of the bug. Handling the return of Indent func,
showed the error. Thanks.

saisreeka...@symantec40.com

unread,
Oct 9, 2015, 5:30:49 PM10/9/15
to golang-nuts, sankar.c...@gmail.com
@Peter 

Thank you! :-) 
Reply all
Reply to author
Forward
0 new messages