type dataOP struct {
Opcode_name string `json:"opcode_name"`
ExeTime int `json:"exeTime"`
}
func main() {
book := dataOP{Opcode_name: "ADD", ExeTime: 5}
byteArray, err := json.Marshal(book)
if err != nil {
fmt.Println(err)
}
f, err := os.OpenFile("./data.json", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
fmt.Println(err)
return
}
n, err := io.WriteString(f, string(byteArray))
if err != nil {
fmt.Println(n, err)
}
}
I want to append data to a json file on new line using Golang. The above code appends the json object one after another, something like
{"opcode_name":"ADD","exeTime":5}{"opcode_name":"ADD","exeTime":5}{"opcode_name":"ADD","exeTime":5}
but i want to append these json objects in new line(json objects separated by new line).
{"opcode_name":"ADD","exeTime":5}
{"opcode_name":"ADD","exeTime":5}
{"opcode_name":"ADD","exeTime":5}
If you want each JSON object to start on a new line, simple write a newline after each object.
Also note that os.File
has a File.Write()
method to write a []byte
, so no need to convert it to string
.
Also don't forget to close the file, preferably deferred:
f, err := os.OpenFile("./data.json", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
n, err := f.Write(byteArray)
if err != nil {
fmt.Println(n, err)
}
if n, err = f.WriteString("\n"); err != nil {
fmt.Println(n, err)
}
Also note that you could write the byte slice and a newline with a single call like this:
if _, err := fmt.Fprintf(f, "%s\n", byteArray); err != nil {
fmt.Println(err)
}