How can I pretty-print JSON using Go?

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

    I was frustrated by the lack of a fast, high quality way to marshal JSON to a colorized string in Go so I wrote my own Marshaller called ColorJSON.

    With it, you can easily produce output like this using very little code:

    package main
    
    import (
        "fmt"
        "encoding/json"
    
        "github.com/TylerBrock/colorjson"
    )
    
    func main() {
        str := `{
          "str": "foo",
          "num": 100,
          "bool": false,
          "null": null,
          "array": ["foo", "bar", "baz"],
          "obj": { "a": 1, "b": 2 }
        }`
    
        var obj map[string]interface{}
        json.Unmarshal([]byte(str), &obj)
    
        // Make a custom formatter with indent set
        f := colorjson.NewFormatter()
        f.Indent = 4
    
        // Marshall the Colorized JSON
        s, _ := f.Marshal(obj)
        fmt.Println(string(s))
    }
    

    I'm writing the documentation for it now but I was excited to share my solution.

提交回复
热议问题