How can I pretty-print JSON using Go?

后端 未结 11 1625
挽巷
挽巷 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:23

    The accepted answer is great if you have an object you want to turn into JSON. The question also mentions pretty-printing just any JSON string, and that's what I was trying to do. I just wanted to pretty-log some JSON from a POST request (specifically a CSP violation report).

    To use MarshalIndent, you would have to Unmarshal that into an object. If you need that, go for it, but I didn't. If you just need to pretty-print a byte array, plain Indent is your friend.

    Here's what I ended up with:

    import (
        "bytes"
        "encoding/json"
        "log"
        "net/http"
    )
    
    func HandleCSPViolationRequest(w http.ResponseWriter, req *http.Request) {
        body := App.MustReadBody(req, w)
        if body == nil {
            return
        }
    
        var prettyJSON bytes.Buffer
        error := json.Indent(&prettyJSON, body, "", "\t")
        if error != nil {
            log.Println("JSON parse error: ", error)
            App.BadRequest(w)
            return
        }
    
        log.Println("CSP Violation:", string(prettyJSON.Bytes()))
    }
    

提交回复
热议问题