Play this article
If we have a JSON string and we need to prettify it without having a struct to unmarshal, we can use:
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
)
func PrettyJSON(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() {
rawJSON := `{"name": "Mike", "lastname": "Tyson"}`
response, err := PrettyJSON(rawJSON)
if err != nil {
log.Fatal(err)
}
fmt.Println(response)
}