How to convert interface to json in Golang?

Hi 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"}

Try it yourself

All the best 👍

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

I'm working on some more Cheat Sheets book on Jquery, TypeScript, React js and for other languages. I will send it once it's completed.

Stay tuned working on React Js Cheat Sheets Book

Related Posts