doukanhua0752 2016-10-28 08:11
浏览 3
已采纳

如何通过(键入* common.MapStr)键入[] byte?

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条回答 默认 最新

  • dsjfrkvn818747 2016-10-28 08:21
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么