In the previous source code example, we have seen how to convert Struct to JSON in Golang. In this source code example, we show how to convert JSON to Struct in Golang with an example.
JSON (JavaScript Object Notation) is a lightweight data interchange format.
In Golang, the encoding/json package implements the encoding and decoding of JSON.
Go - Convert JSON to Struct
In this source code example, we show how to convert JSON to Struct in Golang :
package main
import (
"encoding/json"
"fmt"
"log"
)
type Employee struct {
Id int
FirstName string
LastName string
Email string
}
func main() {
var e1 Employee
data := []byte(`{"Id": 1, "FirstName": "John", "LastName": "Cena", "Email" : "john@gmail.com"}`)
err := json.Unmarshal(data, &e1)
if err != nil {
log.Fatal(err)
}
fmt.Println("Struct is:", e1)
fmt.Println("FirstName: ", e1.FirstName)
fmt.Println("LastName: ", e1.LastName)
fmt.Println("Email: ", e1.Email)
}
Output:
Struct is: {1 John Cena john@gmail.com} FirstName: John LastName: Cena Email: john@gmail.com
Comments
Post a Comment