1

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()
      }
  }
}
Kokizzu
  • 24,974
  • 37
  • 137
  • 233
  • 2
    When you marshal a struct type that does not implement the MarshalJSON or MarshalText methods and has 0 exported fields, what you get is `{}`. It's up to you how you deal with such types. You can convert them to, or wrap them into, types that do implement those methods. Or you can convert them to the desired string representation. – mkopriva Feb 10 '22 at 10:32
  • 1
    See also: https://github.com/amzn/ion-go/issues/170 – mkopriva Feb 10 '22 at 10:42
  • Are you trying to marshal the whole map to Json or marshal it to Ion with a different format for `Timestamp`s? – Matthew Pope Feb 15 '22 at 01:39
  • whole map to json @MatthewPope – Kokizzu Feb 15 '22 at 05:08

1 Answers1

2

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.

Matthew Pope
  • 7,212
  • 1
  • 28
  • 49