How can I pretty-print JSON using Go?
Does anyone know of a simple way to pretty-print JSON output in Go?
The stock http://golang.org/pkg/encoding/json/ package does not seem to include functionality for this (EDIT: it does, see accepted answer) and a quick google doesn't turn up anything obvious.
Uses I'm looking for are both pretty-printing the result of json.Marshal
and just formatting a string full of JSON from wherever, so it's easier to read for debug purposes.
Solution 1:
By pretty-print, I assume you mean indented, like so
{
"data": 1234
}
rather than
{"data":1234}
The easiest way to do this is with MarshalIndent
, which will let you specify how you would like it indented via the indent
argument. Thus, json.MarshalIndent(data, "", " ")
will pretty-print using four spaces for indentation.
Solution 2:
The accepted answer is great if you have an object you want to turn into JSON. The question also mentions pretty-printing just any JSON string, and that's what I was trying to do. I just wanted to pretty-log some JSON from a POST request (specifically a CSP violation report).
To use MarshalIndent
, you would have to Unmarshal
that into an object. If you need that, go for it, but I didn't. If you just need to pretty-print a byte array, plain Indent
is your friend.
Here's what I ended up with:
import (
"bytes"
"encoding/json"
"log"
"net/http"
)
func HandleCSPViolationRequest(w http.ResponseWriter, req *http.Request) {
body := App.MustReadBody(req, w)
if body == nil {
return
}
var prettyJSON bytes.Buffer
error := json.Indent(&prettyJSON, body, "", "\t")
if error != nil {
log.Println("JSON parse error: ", error)
App.BadRequest(w)
return
}
log.Println("CSP Violation:", string(prettyJSON.Bytes()))
}