How to Convert JSON to a Struct in Go

Decode JSON data into a Go struct using the encoding/json.Unmarshal function with a pointer to the target struct.

Use encoding/json.Unmarshal to decode JSON bytes into a pointer to your struct. Define a struct with exported fields and JSON tags matching the keys, then pass the JSON data and the struct pointer to the function.

package main

import (
	"encoding/json"
	"fmt"
)

type User struct {
	Name  string `json:"name"`
	Email string `json:"email"`
}

func main() {
	jsonData := []byte(`{"name":"Alice","email":"alice@example.com"}`)
	var u User
	err := json.Unmarshal(jsonData, &u)
	if err != nil {
		panic(err)
	}
	fmt.Println(u.Name)
}