Skip to content

Instantly share code, notes, and snippets.

@montanaflynn
Last active June 15, 2020 00:21
Show Gist options
  • Save montanaflynn/244e45f2ae597c5ac909712d8c8ec5da to your computer and use it in GitHub Desktop.
Save montanaflynn/244e45f2ae597c5ac909712d8c8ec5da to your computer and use it in GitHub Desktop.
An example of reading a json array from a file and appending a new object to it
package main
import (
"encoding/json"
"io/ioutil"
"os"
)
type User struct {
Username string `json:"username"`
Password string `json:"password"`
}
type Users []User
func main() {
// open the json file with read / write abilities
file, err := os.OpenFile("users.json", os.O_RDWR, 0644)
if err != nil {
panic(err)
}
// good practice to ensure closing the file
defer file.Close()
// read our opened json file into bytes
bytes, err := ioutil.ReadAll(file)
if err != nil {
panic(err)
}
// initialize a Users slice type
var users Users
// unmarshal the bytes into our users type
err = json.Unmarshal(bytes, &users)
if err != nil {
panic(err)
}
// add our new user to the existing users
users = append(users, User{"adam", "test"})
// create new indented JSON with the added user
newBytes, err := json.MarshalIndent(users, "", " ")
if err != nil {
panic(err)
}
// write the new indented json over original file
_, err = file.WriteAt(newBytes, 0)
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment