'ion.Timestamp to json time

I saw that if I store QLDB ion.Timestamp, it cannot be converted directly to json time string (YYYY-MM-DDThh:mm:ss.sssZ).

for example:

// result of querying data object from histories(table, from, to)
var val map[string]interface{} 
err := ion.Unmarshal(tables.GetCurrentData(), &val) // from multiple table
val == map[string]interface {}{
        "createdAt": &ion.Timestamp{
            dateTime: time.Time{
                wall: 0x41cdb40,
                ext:  63746482222,
                loc:  (*time.Location)(nil),
            },
            precision:            0x6,
            kind:                 0x1,
            numFractionalSeconds: 0x3,
        },
        // some other nested column
    }
// val when marshalled to json will show:
{"createdAt":{}}

How to force ion.Timestamp into json string or int64 unix/epoch when marshalled? or I have to check the map recursively whether it's ion.Timestamp or not, then overwrite the map to json string?

current workaround (not yet recursive)

for k, v := range data {
  switch t := v.(type) {
    case ion.Timestamp:
      data[k] = t.String()
    case *ion.Timestamp:
      if t != nil {
        data[k] = t.String()
      }
  }
}


Solution 1:[1]

To convert a Timestamp to JSON in a particular way, you can implement the Marshaler interface for Timestamp.

For example, to convert it as a Unix timestamp, use this function (try it in the Go Playground).

func (t Timestamp) MarshalJSON() ([]byte, error) {
    return json.Marshal(t.GetDateTime().Unix())
}

To convert it as a date string, use this function (try it in the Go Playground).

func (t Timestamp) MarshalJSON() ([]byte, error) {
    return json.Marshal(t.GetDateTime())
}

For further reading, see the documentation for the encoding/json package, or check out this Gopher Academy blog post on advanced encoding and decoding.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matthew Pope