Im trying to loop over JSON data which ive written, as a kind of json database system. Although it does write and read. I can’t seem to access the data it has readed properly
Ive been trying to swap from initaly returning a Message struct to now using a map[string]interface{} since someone on antoher post reccomended that, but its not working.
`package main
import (
"encoding/json"
"log"
"os"
)
type Message struct {
Name string
Body string
Time int64
}
func main() {
foo := Message{"foo", "bar", 1}
writeToFile(foo)
bar := readFromFile()
log.Println(bar)
}
func writeToFile(message Message) {
data, err := json.Marshal(message)
if err != nil {
log.Fatal(err)
}
file, err := os.OpenFile("message.json", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
defer file.Close()
_, err = file.Write(data)
if err != nil {
log.Fatal(err)
}
log.Println("Message written successfully")
}
func readFromFile() Message {
file, err := os.OpenFile("message.json", os.O_RDWR, 0644)
if err != nil {
log.Fatal(err)
}
defer file.Close()
data, err := os.ReadFile("message.json")
if err != nil {
log.Fatal(err)
}
var message Message
json.Unmarshal(data, &message)
return message
}`
New contributor
timmy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.