Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

interface{} to []byte conversion in golang

Tags:

json

go

I am trying to unmarshal a data which is of type interface. So I need to convert the interface type to []byte and pass it to unmarshall. i tried

  1. err := json.Unmarshal([]byte(kpi), &a) => failed
  2. i tired to convert the interface to byte by using kpidata, res := kpi.([]byte) => failed, kpidata is nil

So is there any way we can convert it?

Example: https://play.golang.org/p/5pqQ0DQ94Dp

like image 319
kish Avatar asked Feb 27 '18 10:02

kish


People also ask

How do I assign a byte array in Golang?

To convert String to Byte array in Golang, use the byte() function. A byte is an 8-bit unsigned int. The byte() function takes a string as an input and returns the array.

What is a byte slice in Golang?

Byte slices are a list of bytes that represent UTF-8 encodings of Unicode code points . Taking the information from above, we could create a byte slice that represents the word “Go”: bs := []byte{71, 111} fmt.Printf("%s", bs) // Output: Go. You may notice the %s used here. This converts the byte slice to a string.


2 Answers

In your sample code data should be JSON-encoded (in simple word String) so you are using Unmarshal in a wrong way:

// Unmarshal parses the JSON-encoded data and stores the result // in the value pointed to by v. If v is nil or not a pointer, // Unmarshal returns an InvalidUnmarshalError. func Unmarshal(data []byte, v interface{}) error 

Try it on The Go Playground and this: []string{"art", "football"}:

package main  import (     "encoding/json"     "fmt" )  func main() {     // ********************* Marshal *********************     u := map[string]interface{}{}     u["name"] = "kish"     u["age"] = 28     u["work"] = "engine"     //u["hobbies"] = []string{"art", "football"}     u["hobbies"] = "art"      b, err := json.Marshal(u)     if err != nil {         panic(err)     }     fmt.Println(string(b))      // ********************* Unmarshal *********************     var a interface{}     err = json.Unmarshal(b, &a)     if err != nil {         fmt.Println("error:", err)     }     fmt.Println(a) } 

output:

{"age":28,"hobbies":"art","name":"kish","work":"engine"} map[name:kish work:engine age:28 hobbies:art] 

You want to Unmarshal it, so try this simple working example ([]byte(kpi.(string)):

package main  import (     "encoding/json"     "fmt" )  func main() {     var kpi interface{} = st     var a []Animal     err := json.Unmarshal([]byte(kpi.(string)), &a)     if err != nil {         fmt.Println("error:", err)     }     fmt.Println(a) }  type Animal struct {     Name  string     Order string }  var st = `[     {"Name": "Platypus", "Order": "Monotremata"},     {"Name": "Quoll",    "Order": "Dasyuromorphia"} ]` 

output:

[{Platypus Monotremata} {Quoll Dasyuromorphia}] 

Working example using ([]byte(*kpi.(*string))):

package main  import (     "encoding/json"     "fmt" )  func main() {     var kpi interface{} = &st     var a []Animal     err := json.Unmarshal([]byte(*kpi.(*string)), &a)     if err != nil {         fmt.Println("error:", err)     }     fmt.Println(a) }  type Animal struct {     Name  string     Order string }  var st = `[     {"Name": "Platypus", "Order": "Monotremata"},     {"Name": "Quoll",    "Order": "Dasyuromorphia"} ]` 

Marshal:

package main  import (     "encoding/json"     "fmt" )  func main() {     u := map[string]interface{}{}     u["1"] = "one"     b, err := json.Marshal(u)     if err != nil {         panic(err)     }     fmt.Println(string(b)) } 

output:

{"1":"one"} 

I hope this helps.

like image 170
wasmup Avatar answered Sep 23 '22 06:09

wasmup


Working example based on the one provided by Kugel:

package main  import (     "fmt" )  func passInterface(v interface{}) {     b, ok := v.(*[]byte)     fmt.Println(ok)     fmt.Println(b) }  func main() {     passInterface(&[]byte{0x00, 0x01, 0x02}) } 

Play

If you do not pass references, it will work basically the same:

Play

like image 27
matthias krull Avatar answered Sep 22 '22 06:09

matthias krull