append to a json file in go

To append to a JSON file in Go, you would first need to read the existing JSON data from the file, decode it into a Go data structure, add your new data to the structure, and then encode the updated structure back into JSON format and write it back to the file.

Here's an example code snippet that demonstrates how to do this:

main.go
package main

import (
    "encoding/json"
    "fmt"
    "os"
)

func main() {
    // open the JSON file for reading and writing, create it if it doesn't exist
    file, err := os.OpenFile("data.json", os.O_RDWR|os.O_CREATE, 0644)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer file.Close()

    // decode the existing JSON data into a slice of structs
    var data []SomeStruct
    err = json.NewDecoder(file).Decode(&data)
    if err != nil && err != io.EOF {
        fmt.Println(err)
        return
    }

    // append new data to the slice
    newData := SomeStruct{Field1: "value1", Field2: "value2"}
    data = append(data, newData)

    // encode the updated slice back into JSON format and write it back to the file
    file.Truncate(0) // clear the file
    file.Seek(0, 0)  // set the cursor to the beginning of the file
    err = json.NewEncoder(file).Encode(data)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println("Data appended successfully!")
}

// define your JSON structure as a Go struct
type SomeStruct struct {
    Field1 string `json:"field1"`
    Field2 string `json:"field2"`
}
1163 chars
47 lines

In this example, we first open the JSON file using the os package's OpenFile function, which allows us to specify that we want to read and write to the file and create it if it doesn't exist. We then use Go's built-in JSON encoder and decoder to read the existing JSON data from the file into a slice of SomeStruct objects.

Next, we append our new data to the slice, create a new encoder instance and write the updated slice back to the file using the json.NewEncoder function. Finally, we print a success message to the console.

gistlibby LogSnag