我如何打印(到控制台)的Id,标题,名称等,这个结构在Golang?
type Project struct {
Id int64 `json:"project_id"`
Title string `json:"title"`
Name string `json:"name"`
Data Data `json:"data"`
Commits Commits `json:"commits"`
}
我如何打印(到控制台)的Id,标题,名称等,这个结构在Golang?
type Project struct {
Id int64 `json:"project_id"`
Title string `json:"title"`
Name string `json:"name"`
Data Data `json:"data"`
Commits Commits `json:"commits"`
}
当前回答
fmt.Printf("%+v\n", project)
这是打印细节的基本方法
其他回答
这些包中的大多数都依赖于reflect包来实现这些功能。
fmt.Sprintf()正在使用-> func (p *pp) printArg(参数接口{},动词符文)的标准库
转到第638行-> https://golang.org/src/fmt/print.go
反射:
https://golang.org/pkg/reflect/
示例代码:
https://github.com/donutloop/toolkit/blob/master/debugutil/prettysprint.go
我建议使用json.Unmarshal() 我试着打印id,希望它有帮助:
var jsonString = `{"Id": 1, "Title": "the title", "Name": "the name","Data": "the data","Commits" : "the commits"}`
var jsonData = []byte(jsonString)
var data Project
var err = json.Unmarshal(jsonData, &data)
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Println("Id :", data.Id)
使用包fmt输出非常方便:
fmt.Printf("%+v \n", yourProject)
如果你想看到完整的sturct类型,你可以使用# replace +:
fmt.Printf("%#v \n", yourProject)
我认为应该使用json。MarshalIndent——令人惊讶的是没有建议这样做,因为它是最直接的。例如:
func prettyPrint(i interface{}) string {
s, _ := json.MarshalIndent(i, "", "\t")
return string(s)
}
没有外部deps,结果输出格式很好。
type Response struct {
UserId int `json:"userId"`
Id int `json:"id"`
Title string `json:"title"`
Body string `json:"body"`
}
func PostsGet() gin.HandlerFunc {
return func(c *gin.Context) {
xs, err := http.Get("https://jsonplaceholder.typicode.com/posts")
if err != nil {
log.Println("The HTTP request failed with error: ", err)
}
data, _ := ioutil.ReadAll(xs`enter code here`.Body)
// this will print the struct in console
fmt.Println(string(data))
// this is to send as response for the API
bytes := []byte(string(data))
var res []Response
json.Unmarshal(bytes, &res)
c.JSON(http.StatusOK, res)
}
}