如何将(type *common.MapStr)转换为(type []byte)?

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

How to pass (type *common.MapStr) to type []byte?

问题

抱歉,如果问题太初级的话,因为我昨天才开始学习Go语言。
我试图将publishEvent转换为字节,编译器显示以下错误:

无法将publishEvent(类型*common.MapStr)转换为类型[]byte

有人可以告诉我该怎么做吗?

谢谢。

    var parsed map[string]interface{}
	bytes := []byte(publishEvent) // 在这里出现错误
	err := json.Unmarshal(bytes, &parsed)
    if err != nil{
		fmt.Println("错误:", err)
	}
英文:

Sorry if the question is too newbie, as i just started to learn go yesterday.
I try to convert publishEvent into bytes, and compiler shown error like following:

cannot convert publishEvent (type *common.MapStr) to type []byte

Can anyone show me the way ?

Thank You.

    var parsed map[string]interface{}
	bytes := []byte(publishEvent) --->Error occur here
	err := json.Unmarshal(bytes, &parsed)
    if err != nil{
		fmt.Println("error: ", err)
	}

答案1

得分: 0

我假设你正在使用的结构是common.MapStr,它来自于https://github.com/elastic/libbeat。

common.MapStr已经是一个map[string]interface{},所以我不确定为什么你要将其转换为JSON,然后再解析回相同类型的结构。但如果这是你真正想要做的,你可以将错误行替换为:

bytes, err := json.Marshal(publishEvent)

这样应该可以工作。接下来一行会报错,因为err被重新声明了,所以你需要将其改为:

err = json.Unmarshal(bytes, &parsed)

最终的代码如下(我还添加了另一个错误检查):

var parsed map[string]interface{}
bytes, err := json.Marshal(publishEvent)
if err != nil {
    fmt.Println("error: ", err)
    // 由于无法解析`bytes`,你可能需要在这里退出或返回
}
err = json.Unmarshal(bytes, &parsed)
if err != nil {
    fmt.Println("error: ", err)
}

希望对你有帮助!

英文:

I assume the struct you are working with is common.MapStr from https://github.com/elastic/libbeat

common.MapStr is already a map[string]interface{} so I'm not sure why you are turing it into JSON, and then parsing it back into the same kind of structure, but if thats what you really want to do, replacing the error line with:

bytes, err := json.Marshal(publishEvent)

should work. You will get an error on the next line about redeclaring err so change it to:

err = json.Unmarshal(bytes, &parsed)

Resulting in the following code (also added another error check):

var parsed map[string]interface{}
bytes, err := json.Marshal(publishEvent)
if err != nil{
    fmt.Println("error: ", err)
    // you'll want to exit or return here since we can't parse `bytes`
}
err = json.Unmarshal(bytes, &parsed)
if err != nil{
    fmt.Println("error: ", err)
}

huangapple
  • 本文由 发表于 2016年10月28日 16:11:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/40300769.html
匿名

发表评论

匿名网友

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

确定