我正在尝试制作一个简单的工具,它可以解析文件中以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时间戳时,编组器会抱怨:
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" }
当我进行解析时,编组程序会抱怨这一点:
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
类型,我认为它应该在处理的另一端仍然能够被理解。
我该如何解析这个时间戳以执行数据库插入操作呢?对于问题的长度请谅解,并感谢您的帮助!