IntermediateLesson 11 of 15
Files & JSON – Go
Read and write text, exchange data as JSON.
For small files, os.ReadFile and os.WriteFile are enough. You specify the file permissions as an octal number (0o644 = read/write for you, read for others).
package main
import (
"fmt"
"os"
)
func main() {
err := os.WriteFile("notizen.txt", []byte("Line 1\nLine 2\n"), 0o644)
if err != nil {
panic(err)
}
data, err := os.ReadFile("notizen.txt")
if err != nil {
panic(err)
}
fmt.Print(string(data))
}For large files you read line by line with bufio.Scanner – this keeps memory usage small:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
f, err := os.Open("notizen.txt")
if err != nil {
fmt.Println("Error:", err)
return
}
defer f.Close()
sc := bufio.NewScanner(f)
for sc.Scan() {
fmt.Println(sc.Text())
}
}The encoding/json package converts structs to JSON and back. Struct tags in backticks control the field names; only exported (capitalized) fields are considered.
package main
import (
"encoding/json"
"fmt"
)
type Nutzer struct {
Name string `json:"name"`
Sprachen []string `json:"sprachen"`
Passwort string `json:"-"` // is never serialized
}
func main() {
n := Nutzer{Name: "Ada", Sprachen: []string{"Go", "C"}, Passwort: "secret"}
b, err := json.MarshalIndent(n, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(b))
var zurueck Nutzer
if err := json.Unmarshal(b, &zurueck); err != nil {
panic(err)
}
fmt.Println(zurueck.Name, zurueck.Sprachen) // Ada [Go C]
}TipWith
,omitempty in the tag (json:"alter,omitempty") you omit empty fields. For streams (e.g. HTTP bodies) you use json.NewDecoder(r).Decode(&v) and json.NewEncoder(w).Encode(v).