Home > Back-end >  Unquote string with multiple backslashes
Unquote string with multiple backslashes

Time:11-25

From one source I get data in the following format (with leading double quote)

data := `"{\"u\":\"Mozilla\\\/5.0 (Windows NT 5.1; rv:11.0) Gecko Firefox\\\/11.0 (via ggpht.com GoogleImageProxy)\"}"`
_, err := strconv.Unquote(data)
if err != nil {
    panic(err)
}

I need to unquote and convert it to json. But due to trailing backslashes like here Mozilla\\\/5.0 get error invalid syntax.

In PHP, it is converted via double json_decode like json_decode(json_decode($data, true), true)

How to do the same in go? Unescape this string properly.

CodePudding user response:

The string is double encoded JSON. Use the JSON decoder to remove the quotes:

data := `"{\"u\":\"Mozilla\\\/5.0 (Windows NT 5.1; rv:11.0) Gecko Firefox\\\/11.0 (via ggpht.com GoogleImageProxy)\"}"`
var unquoted string
err := json.Unmarshal([]byte(data), &unquoted)
if err != nil {
    // TODO: handle error
}

Decode a second time to get the user agent string:

var v struct{ U string }
err = json.Unmarshal([]byte(unquoted), &v)
if err != nil {
    // TODO: handle error
}
userAgent := v.U

Run the program on the playground.

CodePudding user response:

can't you just use strings.Trim() and this way remove \ and " chars ? Then you would have to json.Marshall string ?

  •  Tags:  
  • go
  • Related