json - 在 Golang 中完全解析时间戳

标签 json postgresql datetime go unmarshalling

我正在尝试制作一个简单的工具来解析文件中的 JSON 格式的行,并在数据库中执行 INSERT 操作。

我有一个看起来像这样的结构:

type DataBlob struct {
  ....
  Datetime time.Time `json:"datetime, string"`
  ....
}

解析代码如下:

scanner := bufio.NewScanner(file)
// Loop through all lines in the file
for scanner.Scan() {
    var t DataBlob

    // Decode the line, parse the JSON
    dec := json.NewDecoder(strings.NewReader(scanner.Text()))
    if err := dec.Decode(&t);
    err != nil {
        panic(err)
    }

    // Perform the database operation
    executionString: = "INSERT INTO observations (datetime) VALUES ($1)"
    _, err := db.Exec(executionString, t.Datetime)
    if err != nil {
        panic(err)
    }
}

我的 JSON 文件有几行,每一行都包含一个 datetime 值,如下所示:

{ "datetime": 1465793854 }

datetime 被格式化为 Unix 时间戳时,Marshaller 会提示:

panic: parsing time "1465793854" as ""2006-01-02T15:04:05Z07:00"": cannot parse "1465793854" as """

在生成 JSON 的脚本中(也是用 Golang 编写的),我尝试简单地打印 Time.time 类型的字符串表示形式,生成以下内容:

{ "datetime": "2016-06-13 00:23:34 -0400 EDT" }

当我去解析它时 Marshaller 向它提示:

panic: parsing time ""2016-06-13 00:23:34 -0400 EDT"" as ""2006-01-02T15:04:05Z07:00"": cannot parse " 00:23:34 -0400 EDT"" as "T"

如果我也将这个时间戳(看起来很标准)视为字符串并避免编码问题,当我尝试执行插入时 Postgres 会提示:

panic: pq: invalid input syntax for type timestamp: "2016-06-13 00:23:34 -0400 EDT"

这在很多层面上都令人沮丧,但主要是因为如果我序列化一个 Time.time 类型,我认为它仍然应该在过程的另一端被理解。

我怎样才能解析这个时间戳来执行数据库插入?对于冗长的问题深表歉意,感谢您的帮助!

最佳答案

time.Time 的 JSON 解码 expects日期字符串采用 RFC 3339 格式。

所以在生成 JSON 的 golang 程序中,不要简单地打印 time.Time 值,而是使用 Format以 RFC 3339 格式打印。

t.Format(time.RFC3339)

if I serialize a Time.time type, I would think it should still be understood at the other side of the process

如果您使用了 Marshaller interface通过序列化,它确实会以 RFC 3339 格式输出日期。所以流程的另一方会理解它。所以你也可以这样做。

d := DataBlob{Datetime: t}
enc := json.NewEncoder(fileWriter)
enc.Encode(d)

关于json - 在 Golang 中完全解析时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37782278/

相关文章:

javascript - JSON 响应打印 HTML 而不是消息

java - 将 POJO 序列化为 JSON - 输入参数化

PHP JSON 解析,只显示三个参数之一

postgresql - 级联触发器不起作用

java - spring boot postgresql 9.5.3 依赖

javascript - 倒数计时器目标日期隐藏输入字段javascript

java - REST API 插件 - 使用正文而不是查询字符串作为参数

postgresql - 在 PostgreSQL 中分组时如何做三元运算符?

javascript - 在 ng-options 中将 C# dateTime 格式化为 AngularJS 日期

php - ZF2 始终验证日期和时间格式 PT_BR 输入似乎不是有效日期