-2

What happens to my original data in the variable str here? After converting to the struct the length of bytes is 6 And the value of byte don't match ascii code of 1, 2, 3, 4, 5, 6, 7, 8 at all

package main

import (
    "encoding/json"
    "fmt"
)

type Encrypt struct {
    Bytes []byte `json:"bytes"`
}

func main(){
    str := "12345678"
    raw := fmt.Sprintf("{\"bytes\":%s}", str)
    var encrypt = Encrypt{}
    fmt.Println([]byte(raw)[0])
    err := json.Unmarshal([]byte(raw), &encrypt)
    if err != nil{
        fmt.Println(err)
        return
    }
    fmt.Println("final result")
    fmt.Println(len(encrypt.Bytes))
    fmt.Println(string(encrypt.Bytes))
    for _, b := range encrypt.Bytes{
        fmt.Print(b)
        fmt.Print(" ")
    }
    fmt.Print("\n")


}

  • 1
    the "bytes" field of the json is interpreted as one number as the error tells you (12345678). Instead of trying to unmarshal to a byte slice, you could have a look at [json.RawMessage](https://pkg.go.dev/encoding/json#RawMessage), in action e.g. [here](https://stackoverflow.com/q/20101954/10197418). – FObersteiner Aug 16 '21 at 14:11
  • Your JSON is `{"bytes":12345678}`. That's a JSON Number field, not a String field, so there is no reason it would be interpreted as ASCII characters; it's interpreted as a number, because it's presented as a number. – Adrian Aug 16 '21 at 14:19

1 Answers1

0

As per the documentation https://pkg.go.dev/encoding/json#Unmarshal:

To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:

bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null

As you can see there is no place for []byte. Also, in you code raw := fmt.Sprintf("{\"bytes\":%s}", str) you are sending str as a number. You can send it as string as in the following code.

package main

import (
    "encoding/json"
    "fmt"
)

type Encrypt struct {
    ByteString string `json:"bytes"`
}

func main() {
    str := "12345678"
    raw := fmt.Sprintf("{\"bytes\":\"%s\"}", str)
    fmt.Println(raw)
    var encrypt = Encrypt{}

    fmt.Println([]byte(str))

    err := json.Unmarshal([]byte(raw), &encrypt)
    if err != nil {
        panic(err)
    }

    fmt.Println("final result ", []byte(encrypt.ByteString))
}
Nick
  • 1,017
  • 1
  • 10
  • 16