How can I pretty-print JSON using Go?

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

    Here is my solution:

    import (
        "bytes"
        "encoding/json"
    )
    
    const (
        empty = ""
        tab   = "\t"
    )
    
    func PrettyJson(data interface{}) (string, error) {
        buffer := new(bytes.Buffer)
        encoder := json.NewEncoder(buffer)
        encoder.SetIndent(empty, tab)
    
        err := encoder.Encode(data)
        if err != nil {
           return empty, err
        }
        return buffer.String(), nil
    }
    

提交回复
热议问题