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

从字符串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)
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题