How can I pretty-print JSON using Go?

后端 未结 11 1602
挽巷
挽巷 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

    A simple off the shelf pretty printer in Go. One can compile it to a binary through:

    go build -o jsonformat jsonformat.go
    

    It reads from standard input, writes to standard output and allow to set indentation:

    package main
    
    import (
        "bytes"
        "encoding/json"
        "flag"
        "fmt"
        "io/ioutil"
        "os"
    )
    
    func main() {
        indent := flag.String("indent", "  ", "indentation string/character for formatter")
        flag.Parse()
        src, err := ioutil.ReadAll(os.Stdin)
        if err != nil {
            fmt.Fprintf(os.Stderr, "problem reading: %s", err)
            os.Exit(1)
        }
    
        dst := &bytes.Buffer{}
        if err := json.Indent(dst, src, "", *indent); err != nil {
            fmt.Fprintf(os.Stderr, "problem formatting: %s", err)
            os.Exit(1)
        }
        if _, err = dst.WriteTo(os.Stdout); err != nil {
            fmt.Fprintf(os.Stderr, "problem writing: %s", err)
            os.Exit(1)
        }
    }
    

    It allows to run a bash commands like:

    cat myfile | jsonformat | grep "key"
    

提交回复
热议问题