Go Encoding Json

The encoding/json package is used for (un)marshaling JSON data.


Example

package main

import (
    "fmt"
    "encoding/json"
)

type Animal struct {
    Name  string
    Order string
}

func main() {
    file, _ := os.ReadFile("animals.json")

    // Example of unmarshaling data
    var animals []Animal
    err := json.Unmarshal(file, &animals)
    if err != nil {
        fmt.Println("error:", err)
    }

    // Example of marshaling data
    bytes, err := json.Marshal(animals)
    if err != nil {
        fmt.Println("error:", err)
    }

    _ = os.WriteFile("new.json", bytes, 0644)
}


CategoryRicottone

Go/EncodingJson (last edited 2025-10-05 22:16:18 by DominicRicottone)