Skip to content

Instantly share code, notes, and snippets.

@filewalkwithme
Last active March 28, 2018 20:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save filewalkwithme/4778d9f128097065349551041364a9f0 to your computer and use it in GitHub Desktop.
Save filewalkwithme/4778d9f128097065349551041364a9f0 to your computer and use it in GitHub Desktop.
Read JSON from a file, update the content and then write it to the same file again
{"hola":"mundo","number":1}
// To run:
//
// go run main.go
//
// But first, you will need to create a json file called "example.json" with the
// following content:
//
// {"hola":"mundo", "number":1}
//
package main
import (
"encoding/json"
"io/ioutil"
"log"
)
type MyStruct struct {
Hola string `json:"hola"`
Number int `json:"number"`
}
func main() {
// Read the file
buf, err := ioutil.ReadFile("example.json")
if err != nil {
log.Fatal(err)
}
// Unmarshal the content of buf into obj
obj := MyStruct{}
err = json.Unmarshal(buf, &obj)
if err != nil {
log.Fatal(err)
}
// Modify the value
obj.Number = obj.Number + 1
// Marshal obj
buf, err = json.Marshal(obj)
if err != nil {
log.Fatal(err)
}
// Write the marshalled object to the file again
err = ioutil.WriteFile("example.json", buf, 0644)
if err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment