O
O
Oblomov952016-11-21 19:19:57
go
Oblomov95, 2016-11-21 19:19:57

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)

setting.json
{
"Clients" : [
    {
 "ClientId" : "1",
 "Date" : "2016-11-17 12:34"
    },

    {
 "ClientId" : "2",
 "Date" : "2016-11-17 12:33"
    }
]
}

The bottom line is this, I get the id and date from the outside, and I get the following string [{"ClientId":3,"Date":"2016-11-21 18:12"}],
how do I write to my json file?
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2016-11-22
@Oblomov95

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 question

Ask a Question

731 491 924 answers to any question