JSON Serialization and Deserialization in Go

Learn how to serialize Go structs into JSON and deserialize JSON data into Go structs for data exchange and storage.

JSON Serialization and Deserialization in Go
Photo by Chinmay B / Unsplash

Learn how to serialize Go structs into JSON and deserialize JSON data into Go structs for data exchange and storage.

package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name  string `json:"name"`
    Age   int    `json:"age"`
    Email string `json:"email"`
}

func main() {
    // Serialization (struct to JSON)
    person := Person{"Alice", 30, "alice@example.com"}
    jsonData, _ := json.Marshal(person)
    fmt.Println("JSON:", string(jsonData))

    // Deserialization (JSON to struct)
    jsonStr := `{"name":"Bob","age":25,"email":"bob@example.com"}`
    var newPerson Person
    json.Unmarshal([]byte(jsonStr), &newPerson)
    fmt.Println("Name:", newPerson.Name)
}