Home > front end >  How to deal with date fields from JSON in a GO struct
How to deal with date fields from JSON in a GO struct

Time:10-09

I have a JSON content, with some date fields like "resolutiondate" and "created" and "updated" as shown below

{
   "expand":"names,schema",
   "startAt":0,
   "maxResults":50,
   "total":1,
   "issues":[
      {
         "expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields",
         "id":"id",
         "self":"https://url1",
         "key":"key1",
         "fields":{
            "summary":"Summary-1",
            "customfield_10406":null,
            "resolutiondate":"2021-06-10T10:07:35.000 0000",
            "created":"2021-06-10T10:05:24.000 0000",
            "description":"Description-1",
            ...
            ...
            ...
}

I am unmarshalling this JSON data into GO struct and saving the data in a excel sheet. Everything works as expected, the only issue is I'm defining the date fields as string datatypes in my GO struct, as below:

        Resolved           string `json:"resolutiondate,omitempty"`
        Created            string `json:"created,omitempty"`

Hence the final data saved in the excel file looks like:

enter image description here

But I want to save them as date datatype in the excel sheet, in a user defined format-mm/dd/yyyy. How can I effectively use the time package of Golang to achieve this ? Please help.

NOTE: I will be unable to share my complete code and the full JSON file.

CodePudding user response:

For unmarshaling from custom format you need to create time.Time wrapper and implement json.Unmarshaler interface.

type CustomTime struct {
    time.Time
}

func (t *CustomTime) UnmarshalJSON(b []byte) (err error) {
    s := strings.Trim(string(b), "\"")

    date, err := time.Parse("2006-01-02T15:04:05.000-0700", s)
    if err != nil {
        return err
    }
    t.Time = date
    return
}

Now specify your time fields as CustomTime

Resolved           CustomTime `json:"resolutiondate,omitempty"`
Created            CustomTime `json:"created,omitempty"`

For writting into excel you need to provide more info about your implementation.

CodePudding user response:

What you can do is, wrap string as your own custom type, and make it implement the Unmarshaler interface:

type Unmarshaler interface {
    UnmarshalJSON([]byte) error
}

Then take time coming with JSON and parse it to time.Time and format with your custom layout mm/dd/yyyy.

type Date string

func (d *Date) UnmarshalJSON(bytes []byte) error {
    dd, err := time.Parse(`"2006-01-02T15:04:05.000 0000"`, string(bytes))
    if err != nil{
        return err
    }
    *d = Date(dd.Format("01/02/2006"))

    return nil
}

Now you can use

Created            Date `json:"created,omitempty"`

inside your Go struct and unmarshal.

Run sample code here

  • Related