Json help for todo list

I’m working on cli based todolist application, that use command something like this sloth add -m "message". my application that store the task message, id and time as a JSON file like this

{
    "TaskID":"aa9bb19240b1caf0e2a0ec2f6f561874f9140207","TaskMsg":"buy a milk","TaskTime":"1530979782"
}

each and every time sloth add -m "msg" command will fire the data must be store a JSON file
like this

{
    "TaskID":"aa9bb19240b1caf0e2a0ec2f6f561874f9140207","TaskMsg":"buy a milk","TaskTime":"1530979782",
    "TaskID":"ee9bb19240b1caf0e2a0ec2f6f561874f9140207","TaskMsg":"buy butter","TaskTime":"1530979785"
}

one task and other will appended to previous or above the first one, how

The latter JSON has duplicated keys in the object. The last occurence of a key will win over the former, such that your latter example is equivalent to this:

{
    "TaskID":"ee9bb19240b1caf0e2a0ec2f6f561874f9140207","TaskMsg":"buy butter","TaskTime":"1530979785"
}

What I think you really want, is a JSON array:

[
    {"TaskID":"aa9bb19240b1caf0e2a0ec2f6f561874f9140207","TaskMsg":"buy a milk","TaskTime":"1530979782"},
    {"TaskID":"ee9bb19240b1caf0e2a0ec2f6f561874f9140207","TaskMsg":"buy butter","TaskTime":"1530979785"}
]

This is pretty easy by just using a variable of type []T, where T is your original struct.

I assume you already know how you append to slices, but if you do not feel free to ask.

{
 "task":  [ {"TaskID":"aa9bb19240b1caf0e2a0ec2f6f561874f9140207","TaskMsg":"buy a milk","TaskTime":"1530979782"},
    {"TaskID":"c1f9b0be6951cd25814c80cd8bd29228ba6eb5b9","TaskMsg":"buy butter","TaskTime":"1530979785"}
]
}

Hello @Nobbz this is correct okey, How I use [] T for this array because one task is added then the application will exit, again we can fire the command it will work this I’m done it, i need array append

@ajilraju Have you gone through the entire Go Tour guide? https://tour.golang.org/welcome/1

How to use Slices is explained here https://tour.golang.org/moretypes/7 but I recommend you read the entire guide before you take a look, it has a lot of useful information :slight_smile:

How are you storing the JSON? Are you storing the JSON? You need to save your list somewhere, and then read it again whenever your program starts.

I have trouble understanding your notabene, but is there a reason you want to nest the objects? That just adds complexity where it is not necessarily needed.

The general workflow should be like this:

  1. Check if file exists, if not initialize it with an empty JSON-array or object, depending on whatever you decide to use in the end
  2. Read the file and unmarshall into your Go-slice/-struct
  3. Append the new TODO-item to the correct place.
  4. write back the GO-data into the JSON-file.