How can I pretty-print JSON using Go?

Brad Peabody picture Brad Peabody · Sep 26, 2013 · Viewed 157.3k times · Source

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.

Answer

Alexander Bauer picture Alexander Bauer · Sep 26, 2013

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.