1
我想解析一个在python中生成的时间戳,并发布到这里存储在cassandra中,并且出现一个奇怪的错误。解析JSON时间错误
parsing time ""2015-11-05 14:14:32-0700"" as ""2006-01-02T15:04:05Z07:00"": cannot parse " 14:14:32-0700"" as "T"
我不想修改从反正蟒蛇给我的,只是想将它传递直接进入卡桑德拉时间,但司机说我需要它是time.Time
(不串)做所以。
下面是代码
type OurCustomType struct {
TimeStamp time.Time `json:"timestamp"`
}
func extractJsonBody(r *http.Request) []byte {
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
//...
}
if err := r.Body.Close(); err != nil {
//....
}
return body
}
func View(w http.ResponseWriter, r *http.Request) {
var variable OurCustomType
body := extractJsonBody(r)
if err := json.Unmarshal(body, &variable); err != nil {
//..
} else {
//...
}
}
编辑:我已经实现了我自己的time.Time
类型,实现了自定义UnmarshalJSON
试图解决这个问题。
type PythonTime struct {
time.Time
}
func (self *PythonTime) UnmarshalJSON(b []byte) (err error) {
self.Time, err = time.Parse("2006-01-02 15:04:05-0700", string(b))
return
}
但我没有得到这个错误:
parsing time ""2015-11-05 14:14:32-0700"" as "2006-01-02 15:04:05-0700": cannot parse ""2015-11-05 14:14:32-0700"" as "2006"
时间类需要一个格式字符串,在你的情况下它会是'2006-01-02 15:04:05-0700'。我相信你不能直接提供给unmashaller,所以你必须为你的类型实现'UnmarshalJSON'来在那里处理它,或者解组成一个字符串并在稍后转换它。更多关于格式字符串的东西在这里; http://stackoverflow.com/questions/25845172/parsing-date-string-in-golang这里是一个示例实现MarshalJSON,你需要做的是类似的,只是为了解组http://stackoverflow.com/questions/20475321/override-layout-by-json-marshal-to-format-time-time – evanmcdonnal
@evanmcdonnal感谢您的评论,这让我非常接近,但我仍然收到一个我不确定的错误。查看最近的编辑 – electrometro
我不确定如何帮助你。我在这里做了一个快速测试https://play.golang.org/p/fZ7soeHJhj,它应该工作。我通常建议在这里打印/检查'string(b)'的值,因为某些原因格式不匹配,但是错误使得它看起来像'string(b)'正在产生期望值。 – evanmcdonnal