copy a json file in go

To copy a JSON file in Go, you need to open both the source and the target files and then read data from the source file and write it into the target file. Here is an example code to copy JSON file in Go:

main.go
package main

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

func main() {
    // Open the source JSON file
    sourceFile, err := os.Open("source.json")
    if err != nil {
        panic(err)
    }
    defer sourceFile.Close()

    // Read from the source file
    sourceData, err := ioutil.ReadAll(sourceFile)
    if err != nil {
        panic(err)
    }

    // Parse JSON data
    var jsonData interface{}
    err = json.Unmarshal(sourceData, &jsonData)
    if err != nil {
        panic(err)
    }

    // Create the target JSON file
    targetFile, err := os.Create("target.json")
    if err != nil {
        panic(err)
    }
    defer targetFile.Close()

    // Write to the target file
    encoder := json.NewEncoder(targetFile)
    err = encoder.Encode(jsonData)
    if err != nil {
        panic(err)
    }

    fmt.Println("JSON file copied successfully.")
}
890 chars
47 lines

In this code, we first open the source JSON file using the os.Open function, read data from it using the ioutil.ReadAll function, and then parse the JSON data using the json.Unmarshal function.

Then, we create the target JSON file using the os.Create function and write the parsed JSON data into it using the json.NewEncoder and encoder.Encode functions.

Finally, we print a message to indicate that the JSON file has been copied successfully.

gistlibby LogSnag