tobe
tobe

Reputation: 1741

How to convert unicode byte array to normal string in go

I'm getting the byte array from unix socket and try to print as a string. I just string(bytes) and get the following string.

{\"Created\":1410263175,\"Id\":\"f4e36130333537c3725e212f78d603742cf3da4b738272f7232338b0d61fa4fb\",\"ParentId\":\"a8a806a76e3e620a6f2172e401847beb4535b072cf7e60d31e91becc3986827e\",\"RepoTags\":[\"\\u003cnone\\u003e:\\u003cnone\\u003e\"],\"Size\":0,\"VirtualSize\":1260903901}\n,

How can I remove the escape char \ and convert unicode char \u003 into normal string?

Upvotes: 1

Views: 3718

Answers (1)

Thundercat
Thundercat

Reputation: 120951

This looks like a JSON string with \u escapes per the JSON specification. The JSON decoder will take care of unescaping the strings.

The code:

s := "{\"Created\":1410263175,\"Id\":\"f4e36130333537c3725e212f78d603742cf3da4b738272f7232338b0d61fa4fb\",\"ParentId\":\"a8a806a76e3e620a6f2172e401847beb4535b072cf7e60d31e91becc3986827e\",\"RepoTags\":[\"\\u003cnone\\u003e:\\u003cnone\\u003e\"],\"Size\":0,\"VirtualSize\":1260903901}\n"
var m map[string]interface{}
if err := json.Unmarshal([]byte(s), &m); err != nil {
    log.Fatal(err)
}
fmt.Printf("%#v", m)

prints the following (minus the white space that I added for readability):

map[string]interface {}{
     "Created":1.410263175e+09, 
     "Id":"f4e36130333537c3725e212f78d603742cf3da4b738272f7232338b0d61fa4fb",
     "ParentId":"a8a806a76e3e620a6f2172e401847beb4535b072cf7e60d31e91becc3986827e", 
     "RepoTags":[]interface {}{"<none>:<none>"}, 
     "Size":0, 
     "VirtualSize":1.260903901e+09}

playground

The \u escape is not created when converting bytes to a string in Go. It's part of the byte sequence generated by a JSON encoder. The string conversion operator string(byteSlice) converts these bytes to a string as is.

Upvotes: 2

Related Questions