how to convert string to json in golang?
August 11, 2022Hi 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.
Related Tutorials
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
err := json.Unmarshal([]byte(s), &m)
if err != nil {
// panic
}
fmt.Println(s)
}
In the above example
- we have import
"encoding/json"
package to usejson.Unmarshal()
method. - Created JSON ( struct ) type
type Message struct
to use at the time ofjson.Unmarshal()
. - Created sample json string which we will convert in json.
- Used
json.Unmarshal()
method and pased byte string and message struct.
That’s how 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 👍.