Pretty print JSON with json.MarshalIndent

Normally I use json.Marshal when I have some Go data that I want to encode as a string.

bytes, err := json.Marshal(data)

But there’s also json.MarshalIndent which will use newlines and indent the output.

bytes, err := json.MarshalIndent(data, prefix, indent)

For example,

bytes, err := json.MarshalIndent(map[string]int{"a": 1,"b": 2}, "", " ")

produces

{
  "a": 1,
  "b": 2
}

Example from docs.