英文:
How can i print Unmarshalled data in golang?
问题
我正在使用golang从Rabbitmq中读取json,并将json映射到一个接口中。
我的结构体如下所示:
type Documents struct {
user_id string
partner_id []string
last_login int
}
我正在将传入的json映射到上述结构体中,但是为了调试目的,我想要查看接口数组,我应该如何打印映射后的数据数组(在我的情况下是body
)?
var body []Documents
json.Unmarshal(d.Body, &body)
log.Printf("Received a message: %v", body)
在这里,你可以使用%v
作为格式化标识符来打印接口数组。
英文:
I am reading json from Raabbitmq in golang and mapping the json in an interface
My struct looks like this, and
type Documents struct {
user_id string
partner_id []string
last_login int
}
and I am mapping the incoming json in the above struct, but for debugginf purpose, i want to see the interface array , how can i print the mapped data array (body in my case )
var body []Documents
json.Unmarshal(d.Body, &body)
log.Printf("Received a message: %s", body)
Do i need to put other identifier instead of %s ?
答案1
得分: 5
你的结构定义有问题。你需要使用导出的标识符,像这样:
type Documents struct {
UserID string `json:"user_id"`
PartnerID []string `json:"partner_id"`
LastLogin int `json:"last_login"`
}
关于你的问题,可以参考打印动词格式。
打印body的值:
log.Printf("Received a message: %v", body)
打印变量名和值:
log.Printf("Received a message: %#v", body)
英文:
You have problem with your struct definition. You need use Exported identifier, like-
type Documents struct {
UserID string `json:"user_id"`
PartnerID []string `json:"partner_id"`
LastLogin int `json:"last_login"`
}
For your question, refer to format printing verbs.
To print values of body-
log.Printf("Received a message: %v", body)
To print values along with variable name -
log.Printf("Received a message: %#v", body)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论