In everyday programming work (especially as a web developer), you often have to debug and analyze JSON responses. In such cases, it is good to display them with an appropriate indentation for better readability, which is often called pretty printing or beautifying JSON. In Go, we can do this in several ways using the encoding/json
package.
JSON pretty print by marshaling value
Function json.MarshalIndent
generates JSON encoding of the value with indentation. You can specify a prefix
of each JSON line and indent
copied one or more times according to the indentation level. In our example, we pretty-print JSON using four spaces for indentation.
package main
import (
"encoding/json"
"fmt"
"log"
)
func PrettyStruct(data interface{}) (string, error) {
val, err := json.MarshalIndent(data, "", " ")
if err != nil {
return "", err
}
return string(val), nil
}
type Fruit struct {
Name string `json:"name"`
Color string `json:"color"`
}
func main() {
fruit := Fruit{
Name: "Strawberry",
Color: "red",
}
res, err := PrettyStruct(fruit)
if err != nil {
log.Fatal(err)
}
fmt.Println(res)
}
JSON pretty print by encoding value
If you use json.Encode
, you can set indentation through Encoder.SetIndent
method similarly to as in marshaling, by defining a prefix
and indent
.
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
)
func PrettyEncode(data interface{}, out io.Writer) error {
enc := json.NewEncoder(out)
enc.SetIndent("", " ")
if err := enc.Encode(data); err != nil {
return err
}
return nil
}
type Fruit struct {
Name string `json:"name"`
Color string `json:"color"`
}
func main() {
fruit := Fruit{
Name: "Strawberry",
Color: "red",
}
var buffer bytes.Buffer
err := PrettyEncode(fruit, &buffer)
if err != nil {
log.Fatal(err)
}
fmt.Println(buffer.String())
}
Pretty print JSON string
Package encoding/json
also has a useful function json.Indent
to beautify JSON string without indentation to JSON with indentation. The function needs the source JSON, output buffer, prefix
, and indent
.
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
)
func PrettyString(str string) (string, error) {
var prettyJSON bytes.Buffer
if err := json.Indent(&prettyJSON, []byte(str), "", " "); err != nil {
return "", err
}
return prettyJSON.String(), nil
}
func main() {
fruitJSON := `{"name": "Strawberry", "color": "red"}`
res, err := PrettyString(fruitJSON)
if err != nil {
log.Fatal(err)
}
fmt.Println(res)
}
All methods print JSON string with indentation:
{
"name": "Strawberry",
"color": "red"
}