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.

Answer from wasmup on Stack Overflow
Top answer
1 of 2
25

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.

2 of 2
10

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

🌐
GitHub
gist.github.com › miguelmota › 5bfa2b6ab88f439fe0da0bfb1faca763
Golang interface to bytes using gob encoder · GitHub
To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters ... func GetBytes(key interface{}) ([]byte, error) { buf, ok := key.([]byte) if !ok { return nil, fmt.Errorf("ooops, did not work") } return buf, nil }
Discussions

go - Convert arbitrary Golang interface to byte array - Stack Overflow
I'm trying to write a hash that will accept all datatypes. Once in the function, I handle the data as a byte array. I'm having trouble figuring out how to cast an arbitrary interface{} to a byte ar... More on stackoverflow.com
🌐 stackoverflow.com
Use Bytes() instead of Interface().([]byte) for reflect.Slice marshalling
When trying to marshal field with custom type that has bytearray underneath (like datatypes.JSON from GORM) I get this: interface conversion: interface {} is datatypes.JSON, not []uint8 · In our mocks I replaced the following line: [/marshal.go]( More on github.com
🌐 github.com
1
July 12, 2022
Use []T as []interface{}
If T can be assigned to interface{}, then why []T can’t be assigned to []interface{} · The issue is that the memory layout of a []rune is completely different than that of []interface{}. A []rune contains a pointer to an array of 4-byte runes positioned back-to-back in memory. More on forum.golangbridge.org
🌐 forum.golangbridge.org
10
0
October 9, 2020
go - How to convert interface{} to bytes.Buffer - Stack Overflow
Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... New site design and philosophy for Stack Overflow: Starting February 24, 2026... I’m Jody, the Chief Product and Technology Officer at Stack Overflow. Let’s... 1 storing and retrieving byte representation of interface... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GitHub
github.com › aerospike › aerospike-client-go › issues › 382
Use Bytes() instead of Interface().([]byte) for reflect.Slice marshalling · Issue #382 · aerospike/aerospike-client-go
July 12, 2022 - When trying to marshal field with custom type that has bytearray underneath (like datatypes.JSON from GORM) I get this: interface conversion: interface {} is datatypes.JSON, not []uint8 · In our mocks I replaced the following line: [/marshal.go]( aerospike-client-go/marshal.go ·
Author: aerospike
🌐
Go Packages
pkg.go.dev › github.com › pericles-luz › go-converter › pkg › converter
converter package - github.com/pericles-luz/go-converter/pkg/converter - Go Packages
September 11, 2023 - func StructToMapInterface(data ... is empty. func AssetToBase64(path string) string · Convert a file to a base64 string · func ByteToMapInterface(bytes []byte) map[string]interface{} Convert a byte sequence to a map[string]string ·...
🌐
Go
go.dev › play › p › P-BM9QdYjG
Go Playground - The Go Programming Language
The playground can use most of the standard library, with some exceptions. The only communication a playground program has to the outside world is by writing to standard output and standard error.
🌐
YourBasic
yourbasic.org › golang › conversions
Conversions [complete list] · YourBasic Go
All Go conversions (casts): interfaces, strings, integers, floats, byte slices, rune slices, underlying type, implicit conversions and pointers.
Find elsewhere
🌐
YouTube
m.youtube.com › shorts › i4I4la437AI
Convert map[string]interface{}) to []byte In Go
Share your videos with friends, family, and the world
Published: February 3, 2023
🌐
Go Packages
pkg.go.dev › bytes
bytes package - bytes - Go Packages
Package bytes implements functions for the manipulation of byte slices.
🌐
Go Forum
forum.golangbridge.org › getting help
Use []T as []interface{} - Getting Help - Go Forum
October 9, 2020 - If T can be assigned to interface{}, then why []T can’t be assigned to []interface{} · The issue is that the memory layout of a []rune is completely different than that of []interface{}. A []rune contains a pointer to an array of 4-byte runes positioned back-to-back in memory.
🌐
Aguidehub
aguidehub.com › blog › 2022-08-31-golang-convert-interface-to-byte
how to convert interface to byte in golang?
August 31, 2022 - Example of change background color of mui table in React js with step by step tutorial - aGuideHubMarch 21, 20244 minsReactHow to set max width of mui table in react js · Example of set max width of mui table in React js with step by step tutorial - aGuideHubMarch 20, 20244 minsReactHow to ...
🌐
YouTube
youtube.com › watch
Convert map[string]interface{}) to []byte In Go - YouTube
Learn how to convert map of type map[string]interface{}) to byte slice of type []byte in GoLang.In Go, you can convert a map of type map[string]interface{} t...
Published: February 4, 2023
🌐
php.cn
m.php.cn › home › backend development › golang › golang interface convert bytes
golang interface convert bytes-Golang-php.cn
May 15, 2023 - Golang provides two basic types to handle byte type data: byte and []byte. Where byte is an 8-bit unsigned integer type, which can be used to represent ASCII characters or binary data. []byte is a dynamic array type that can be used to store byte arrays of any length. The conversion of interface type and byte type in Golang usually involves the following three situations:
🌐
Google
golang.google.cn › pkg › bytes
Package bytes - The Go Programming Language - Google
Read implements the io.Reader interface. func (r *Reader) ReadAt(b []byte, off int64) (n int, err error)
🌐
gosamples
gosamples.dev › tutorials › convert byte slice to io. reader in go
📚 Convert byte slice to io.Reader in Go
September 15, 2021 - package main import ( "bytes" "fmt" "log" ) func main() { data := []byte("test byte slice") // byte slice to bytes.Reader, which implements the io.Reader interface reader := bytes.NewReader(data) // read the data from reader buf := make([]byte, len(data)) if _, err := reader.Read(buf); err != nil { log.Fatal(err) } fmt.Println(string(buf)) }
🌐
Go
go.dev › tour › methods › 21
io.Reader interface
Where to Go from here... The io package specifies the io.Reader interface, which represents the read end of a stream of data. The Go standard library contains many implementations of this interface, including files, network connections, compressors, ciphers, and others. ... Read populates the given byte slice with data and returns the number of bytes populated and an error value.
🌐
GitHub
github.com › golang › go › issues › 64814
proposal: spec: allow convert ~[]interface{~byte|~rune} to string · Issue #64814 · golang/go
December 20, 2023 - Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session. ... Currently we have generics, but can't convert byte or rune slice to string.
Author: golang