Go Encoding Json
The encoding/json package is used for (un)marshaling JSON data.
Contents
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)
}