-
-
Save udhos/a8e50d5dcf128dda81f0a74683e40837 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{"hola":"mundo","number":1} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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