Created
June 19, 2018 17:49
-
-
Save montanaflynn/4e5d35d98f460e44d97e34c172a4d7be 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
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
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 json 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