How can I pretty-print JSON using Go?

后端 未结 11 1608
挽巷
挽巷 2020-12-07 08:12

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 functiona

11条回答
  •  遥遥无期
    2020-12-07 08:21

    Here's what I use. If it fails to pretty print the JSON it just returns the original string. Useful for printing HTTP responses that should contain JSON.

    import (
        "encoding/json"
        "bytes"
    )
    
    func jsonPrettyPrint(in string) string {
        var out bytes.Buffer
        err := json.Indent(&out, []byte(in), "", "\t")
        if err != nil {
            return in
        }
        return out.String()
    }
    

提交回复
热议问题