How can I pretty-print JSON using Go?

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

    i am sort of new to go, but this is what i gathered up so far:

    package srf
    
    import (
        "bytes"
        "encoding/json"
        "os"
    )
    
    func WriteDataToFileAsJSON(data interface{}, filedir string) (int, error) {
        //write data as buffer to json encoder
        buffer := new(bytes.Buffer)
        encoder := json.NewEncoder(buffer)
        encoder.SetIndent("", "\t")
    
        err := encoder.Encode(data)
        if err != nil {
            return 0, err
        }
        file, err := os.OpenFile(filedir, os.O_RDWR|os.O_CREATE, 0755)
        if err != nil {
            return 0, err
        }
        n, err := file.Write(buffer.Bytes())
        if err != nil {
            return 0, err
        }
        return n, nil
    }
    

    This is the execution of the function, and just standard

    b, _ := json.MarshalIndent(SomeType, "", "\t")
    

    Code:

    package main
    
    import (
        "encoding/json"
        "fmt"
        "io/ioutil"
        "log"
    
        minerals "./minerals"
        srf "./srf"
    )
    
    func main() {
    
        //array of Test struct
        var SomeType [10]minerals.Test
    
        //Create 10 units of some random data to write
        for a := 0; a < 10; a++ {
            SomeType[a] = minerals.Test{
                Name:   "Rand",
                Id:     123,
                A:      "desc",
                Num:    999,
                Link:   "somelink",
                People: []string{"John Doe", "Aby Daby"},
            }
        }
    
        //writes aditional data to existing file, or creates a new file
        n, err := srf.WriteDataToFileAsJSON(SomeType, "test2.json")
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println("srf printed ", n, " bytes to ", "test2.json")
    
        //overrides previous file
        b, _ := json.MarshalIndent(SomeType, "", "\t")
        ioutil.WriteFile("test.json", b, 0644)
    
    }
    

提交回复
热议问题