如何在Golang中打印反序列化的数据?

huangapple go评论159阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2017年7月7日 15:10:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/44964648.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定