Pretty-Print JSON in Go with json.MarshalIndent
Pretty-print JSON in Go with json.MarshalIndent(v, "", " "). It escapes <, > and & as unicode sequences, which Encoder.SetEscapeHTML(false) turns off.
You print a struct as indented JSON for a log or a file, and the angle brackets in a value come out as strange escape sequences.
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
v := map[string]string{"cmd": "a < b && c > d"}
b, _ := json.MarshalIndent(v, "", " ")
fmt.Println(string(b))
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
enc.SetEscapeHTML(false)
enc.Encode(v)
}{
"cmd": "a \u003c b \u0026\u0026 c \u003e d"
}
{
"cmd": "a < b && c > d"
}MarshalIndent formats with the prefix and indent you give. By default the encoder replaces <, > and & with unicode escape sequences, as the first block of output shows, so the output is safe to embed in HTML, and the escaped form is valid JSON that decodes back to the same text. SetEscapeHTML(false) on an Encoder writes them raw, as the second block of output shows. Both are in the encoding/json documentation.
There is no escape switch on MarshalIndent itself, so use the encoder for the raw form. Encode adds a trailing newline, which Marshal does not. Map keys are sorted, so the order of the output is stable, while struct fields come out in declaration order. To reformat existing JSON bytes, json.Indent does it without decoding.