New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
encoding/json: Wrong []uint8 marshal #16815
Comments
Hello there @mr4x. TL;DR string([]byte{42, 42}) and []byte{42, 42} are not of the same type. AnalysisYour code sample at https://play.golang.org/p/gQ7NbCR7dQ, and inlined below: package main
import (
"encoding/json"
"fmt"
)
func main() {
b, err := json.Marshal([]byte{42, 42})
if err != nil {
fmt.Println("error:", err)
}
fmt.Println(b, string(b))
} which when run gives [34 75 105 111 61 34] "Kio=" []byte(42, 42) != string([]byte(42, 42))
where string([]byte(42, 42)) == "**".
When the string value is marshaled, it still gives "**" which is what you were expecting, since the marshaled value of a string is itself and so is a directly converted string value, with no transformations. But that only applies when we are dealing with strings and not byte slices. Therefore: if you then unmarshaled the originally encoded bytes as a []byte and printed out the value, you'd get back package main
import (
"bytes"
"encoding/json"
"fmt"
)
func main() {
origB := []byte{42, 42}
marshaledB, err := json.Marshal(origB)
if err != nil {
fmt.Println("error:", err)
}
fmt.Println(marshaledB, string(marshaledB))
var liveB []byte
var s string
if err := json.Unmarshal(marshaledB, &liveB); err != nil {
fmt.Printf("err: %v\n", err)
}
_ = json.Unmarshal(marshaledB, &s)
if !bytes.Equal(liveB, origB) {
fmt.Printf("failed to get back original value liveB: %v(%s) origB: %v(%s)\n", liveB, origB)
}
fmt.Printf("liveB:: raw: %v string: %s stringFromOriginallyEncodedBytes: %s\n", liveB, liveB, s)
} Giving [34 75 105 111 61 34] "Kio="
liveB:: raw: [42 42] string: ** stringFromOriginallyEncodedBytes: Kio= |
@odeke-em thanks for the explanation |
Please answer these questions before submitting your issue. Thanks!
go version
)?go1.7
go env
)?darwin/amd64
play.golang.org
[]uint8{42, 42}
or at least"**"
[34 75 105 111 61 34]
and"Kio="
The text was updated successfully, but these errors were encountered: