How can I pretty-print JSON using Go?

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

    //You can do it with json.MarshalIndent(data, "", "  ")
    
    package main
    
    import(
      "fmt"
      "encoding/json" //Import package
    )
    
    //Create struct
    type Users struct {
        ID   int
        NAME string
    }
    
    //Asign struct
    var user []Users
    func main() {
     //Append data to variable user
     user = append(user, Users{1, "Saturn Rings"})
     //Use json package the blank spaces are for the indent
     data, _ := json.MarshalIndent(user, "", "  ")
     //Print json formatted
     fmt.Println(string(data))
    }
    

提交回复
热议问题