Skip to content

Instantly share code, notes, and snippets.

@GeoffWilliams
Created August 24, 2018 23:47
Show Gist options
  • Save GeoffWilliams/9993a4b6c0e54afda1c89711fea9f436 to your computer and use it in GitHub Desktop.
Save GeoffWilliams/9993a4b6c0e54afda1c89711fea9f436 to your computer and use it in GitHub Desktop.
read and write JSON to file using golang
package main
import (
"encoding/json"
"io/ioutil"
"os"
"log"
)
type Person struct {
Name string `json:"Name"`
Age int `json:"Age"`
}
var stderr = log.New(os.Stderr, "RUHROH-->", 0)
func main() {
// age 10 years :(
var person Person = load("test.json")
for i := 0; i < 10; i++ {
person.Age += 1
save("test.json", person)
}
}
func load(filename string) Person {
var person Person
data, err := ioutil.ReadFile(filename)
// f, err := os.Open(filename)
if err == nil {
err = json.Unmarshal(data, &person)
if err != nil {
stderr.Println("parsing config file", err.Error())
}
} else {
stderr.Println("opening json file", err.Error())
}
return person
}
func save(filename string, person Person) {
json, err := json.Marshal(person)
if err == nil {
err = ioutil.WriteFile(filename, []byte(json), 0644)
if err != nil {
stderr.Println(err)
}
} else {
stderr.Println(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment