Answer the question
In order to leave comments, you need to log in
How to add an entry to json in Go?
func (y Yml) GetDate() string {
ymlDate := y.Date
return ymlDate
}
sYmlDate := p.GetDate()
var date = Clients{
{ClientId: sId, Date: sYmlDate},
}
data, err := json.Marshal(&date)
if err != nil {
log.Fatalf("JSON marshaling failed: %s", err)
}
fmt.Printf("%s\n", data)
{
"Clients" : [
{
"ClientId" : "1",
"Date" : "2016-11-17 12:34"
},
{
"ClientId" : "2",
"Date" : "2016-11-17 12:33"
}
]
}
Answer the question
In order to leave comments, you need to log in
First we parse the settings file into the structure, then we add a new client there, then we marshall it back into json.
package main
import (
"encoding/json"
"io/ioutil"
"log"
)
type Client struct {
ClientId string
Date string
}
type Settings struct {
Clients []Client
}
const settingsFilename = "settings.json"
func main() {
rawDataIn, err := ioutil.ReadFile(settingsFilename)
if err != nil {
log.Fatal("Cannot load settings:", err)
}
var settings Settings
err = json.Unmarshal(rawDataIn, &settings)
if err != nil {
log.Fatal("Invalid settings format:", err)
}
newClient := Client{
ClientId: "123",
Date: "2016-11-17 12:34",
}
settings.Clients = append(settings.Clients, newClient)
rawDataOut, err := json.MarshalIndent(&settings, "", " ")
if err != nil {
log.Fatal("JSON marshaling failed:", err)
}
err = ioutil.WriteFile(settingsFilename, rawDataOut, 0)
if err != nil {
log.Fatal("Cannot write updated settings file:", err)
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question