how to convert json to struct in golang?
September 03, 2022Hi Friends 👋,
Welcome To aGuideHub! ❤️
To convert json to struct in golang, use json.Unmarshal()
, it will convert json string to struct. You have to only pass your json in json.Unmarshal()
.
Related Tutorials
Today, I will show you how do I convert a json string to struct in golang, as above mentioned I’m going to use json.Unmarshal()
with byte
method.
Let’s start our Golang convert json to struct example
main.go
package main
import (
"encoding/json"
"fmt"
)
type Domain struct {
Id int
Name string
}
// main function
func main() {
var domain Domain
Data := []byte(`{
"Id": 1,
"Name": "Infinitbility"
}`)
err := json.Unmarshal(Data, &domain)
if err != nil {
fmt.Println(err)
}
// printing details of
// decoded data
fmt.Println("Struct is:", domain)
fmt.Println("Name is:", domain.Name)
}
In the above example, we have converted the json value to a struct and printed in golang console. let’s check the output.
Output
Struct is: {1 Infinitbility}
Name is: Infinitbility
I hope it helps you, All the best 👍.