dongyuan7981 2017-12-31 04:22
浏览 3099
已采纳

从字符串golang中删除转义的双引号

This my json string

var jsonBytes = "\"[{\"Fld1\":10,\"Fld2\":\"0.2\"},{\"Fld1\":10,\"Fld2\":\"0.26
\"}]\""

This string has escaped double quotes. If I Unmarshal it by converting to []bytes, its not working, as the convereted []byte array still has leading and trailing double quotes.

How do I remove those leading and trailing quotes in go?

  • 写回答

1条回答 默认 最新

  • dsgm5631 2017-12-31 07:14
    关注
    • First mistake is you have enter in your jsonBytes. remove that near "0.26
    • you have \ in the first and the last data. I will show you to remove it below :

    `

    package main
    
    import (
        "encoding/json"
        "fmt"
        "log"
        "reflect"
    
        "github.com/Gujarats/logger"
    )
    
    type Msg struct {
        Channel int    `json:"Fld1"`
        Name    string `json:"Fld2"`
        Msg     string
    }
    
    func main() {
        var msg []Msg
        var jsonBytes = "\"[{\"Fld1\":10,\"Fld2\":\"0.2\"},{\"Fld1\":10,\"Fld2\":\"0.26\"}]\""
    
        // Removing the the first and the last '\'
        newVal := jsonBytes[1 : len(jsonBytes)-1]
        logger.Debug("newval type ", reflect.TypeOf(newVal))
        logger.Debug("newval ", newVal)
    
    
        err := json.Unmarshal([]byte(newVal), &msg)
        if err != nil {
            log.Fatal(err)
        }
    
        fmt.Printf("%+v
    ", msg)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮