Hi Friends 👋,
Welcome To aGuideHub! ❤️
To convert String to json in golang, use the json.Unmarshal()
method it will convert your string to JSON and return the converted JSON object.
Follow the below tutorial if you are struggling with installing GO in windows.
https://aguidehub.com/blog/how-to-install-golang-in-windows
Today, I will show you how do i Convert String to JSON in golang, as above mentioned I’m going to use the json.Unmarshal()
method.
To use the json.Unmarshal()
method, we have first import "encoding/json"
package which is built in provided by golang, then we have to pass our string as a byte array with an assignable variable.
Let’s start our Golang convert string to JSON example
main.go
package main
import (
"encoding/json"
"fmt"
)
type Message struct {
Name string
Version int64
}
func main() {
s := `{"name":"Android", "version":13, "code":1}`
var m Message
// func Unmarshal(data []byte, v interface{}) error
err := json.Unmarshal([]byte(s), &m)
if err != nil {
// panic
}
fmt.Println(s)
}
In the above example, we have converted a string to JSON and printed it in the console. let’s check the output.
Output
{"name":"Android", "version":13, "code":1}
I hope it helps you, All the best 👍.