1

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @tumahai and you're right. It's a JSON bytes. Can you give a demo to convert bytes to string rather than using map?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.