write to a json file in go

To write to a JSON file in Go, you will need to use the encoding/json package, along with the standard os package.

Here's a sample code snippet that demonstrates how to write JSON data to a file:

main.go
package main

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

func main() {
    // create an example data structure
    data := struct {
        Name    string
        Age     int
        Address string
    }{
        Name:    "John Doe",
        Age:     32,
        Address: "123 Main St.",
    }

    // create a file to write JSON data to
    file, err := os.Create("data.json")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer file.Close()

    // create a JSON encoder that will write to the file
    encoder := json.NewEncoder(file)

    // encode the data structure and write it to the file
    err = encoder.Encode(data)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println("JSON data written to file.")
}
775 chars
41 lines

In this example, we first create a data structure that we want to write to a JSON file. Then, we create a file using the os.Create function, and make sure to close the file after we're done writing data to it. We then create a JSON encoder using the json.NewEncoder function, passing in the file we want to write to. Finally, we call the Encode method to encode the data structure and write it to the file. If any errors occur during the process, we print the error to the console.

related categories

gistlibby LogSnag