Skip to content

Instantly share code, notes, and snippets.

@GeoffWilliams
Last active August 25, 2018 08:27
Show Gist options
  • Save GeoffWilliams/52d1401fc5305c382f3e676403a23a9b to your computer and use it in GitHub Desktop.
Save GeoffWilliams/52d1401fc5305c382f3e676403a23a9b to your computer and use it in GitHub Desktop.
read/write json from a map to a file. Why use a struct over a map? ... if you need to mix datatypes (hmm... dont... - use interface{}) you have to
package main
import (
"encoding/json"
"io/ioutil"
"os"
"log"
)
var stderr = log.New(os.Stderr, "RUHROH-->", 0)
func main() {
// age 10 years :(
var dataMap map[string]int = load("testmap.json")
for i := 0; i < 10; i++ {
dataMap["Age"] += 1
save("testmap.json", dataMap)
}
}
func load(filename string) map[string]int {
dataMap := make(map[string]int)
data, err := ioutil.ReadFile(filename)
// f, err := os.Open(filename)
if err == nil {
err = json.Unmarshal(data, &dataMap)
if err != nil {
stderr.Println("parsing config file", err.Error())
}
} else {
stderr.Println("opening json file", err.Error())
}
return dataMap
}
func save(filename string, dataMap map[string]int) {
json, err := json.Marshal(dataMap)
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