How to convert interface to json in Golang?
December 10, 2022Hi Friends 👋,
Welcome To aGuideHub! ❤️
In Go, you can convert an interface to JSON by first converting it to a type that can be serialized to JSON, such as a map or a struct, and then using the json.Marshal()
function to convert it to JSON.
Here is an example of how to convert an interface to JSON in Go:
package main
import (
"fmt"
"encoding/json"
)
type MyInterface interface {
SomeMethod()
}
type MyType struct {
SomeField string
}
func (t *MyType) SomeMethod() {}
func main() {
// create a value of type MyInterface
var i MyInterface
i = &MyType{"Hello World"}
// convert the interface value to a map
m := map[string]interface{}{
"SomeField": i.(*MyType).SomeField,
}
// convert the map to JSON
b, err := json.Marshal(m)
if err != nil {
panic(err)
}
fmt.Println(string(b))
}
In this example, we have an interface type called MyInterface
and a type called MyType
that implements this interface. We then create a value of type MyInterface
and convert it to a map
using a type assertion. This allows us to create a map that contains the data from the original MyType value.
Finally, we use the json.Marshal()
function to convert the map to JSON. This returns a byte slice containing the JSON data, which we then convert to a string and print to the console.
Output:
{"SomeField":"Hello World"}
All the best 👍