英文:
ion.Timestamp to json time
问题
我看到如果我存储 QLDB 的 ion.Timestamp
,它不能直接转换为 JSON 时间字符串 (YYYY-MM-DDThh:mm:ss.sssZ
)。
例如:
// 从历史记录表中查询数据对象的结果
var val map[string]interface{}
err := ion.Unmarshal(tables.GetCurrentData(), &val) // 来自多个表
val == map[string]interface{}{
"createdAt": &ion.Timestamp{
dateTime: time.Time{
wall: 0x41cdb40,
ext: 63746482222,
loc: (*time.Location)(nil),
},
precision: 0x6,
kind: 0x1,
numFractionalSeconds: 0x3,
},
// 其他嵌套列
}
// 将 val 编组为 JSON 时将显示:
{"createdAt":{}}
如何在编组时将 ion.Timestamp
强制转换为 JSON 字符串或 int64 的 Unix/Epoch 时间?
或者我必须递归地检查映射是否为 ion.Timestamp
,然后将映射覆盖为 JSON 字符串?
当前的解决方法(尚未递归):
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()
}
}
}
英文:
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()
}
}
}
答案1
得分: 2
要将Timestamp
转换为特定的JSON格式,可以为Timestamp
实现Marshaler
接口。
例如,要将其转换为Unix时间戳,可以使用以下函数(在Go Playground中尝试)。
func (t Timestamp) MarshalJSON() ([]byte, error) {
return json.Marshal(t.GetDateTime().Unix())
}
要将其转换为日期字符串,可以使用以下函数(在Go Playground中尝试)。
func (t Timestamp) MarshalJSON() ([]byte, error) {
return json.Marshal(t.GetDateTime())
}
如需进一步了解,请参阅encoding/json
包的文档,或查看Gopher Academy博客上关于高级编码和解码的文章。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论