Skip to content

Instantly share code, notes, and snippets.

@justinschuldt
Created November 22, 2021 20:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinschuldt/e3241c33166e996367d86fbd41ce354f to your computer and use it in GitHub Desktop.
Save justinschuldt/e3241c33166e996367d86fbd41ce354f to your computer and use it in GitHub Desktop.
Golang add key/value to json file
package main
import (
"encoding/json"
"log"
"os"
"sync"
)
type Exclude struct {
Exclude map[string]string `json:"exclude"`
}
func addToFile(file, key, value string, mu sync.RWMutex) {
mu.Lock()
fileData, _ := os.ReadFile(file)
excluded := Exclude{}
unmarshalErr := json.Unmarshal(fileData, &excluded)
if unmarshalErr != nil {
log.Fatalf("failed unmarshaling excludeFile %v", excludeFile)
}
// add value
excluded.Exclude[key] = value
// now Marshal it
excludedBytes, marshalErr := json.MarshalIndent(excluded, "", " ")
if marshalErr != nil {
log.Fatal("failed marshaling exluded json.")
}
writeErr := os.WriteFile(file, excludedBytes, 0666)
mu.Unlock()
if writeErr != nil {
log.Fatal("failed writing to file", err)
}
log.Println("done writing to file.")
}
func main() {
var fileMutex sync.RWMutex
file := "/home/justin/exclusions.json"
addToFile(file, "foo", "bar", fileMutex)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment