2017-09-25 39 views
0

我正在使用simplejson,它提供了类型断言器。golang simplejson mustint64不会从字符串转换为int64

fmt.Printf("%s %s", m.Get("created_time").MustString(), m.Get("created_time").MustInt64()) 

上面的代码示出了该结果:

1506259900 %!s(int64=0) 

所以MustInt64()给出了0,而不是转换的Int64值。

是否因为1506259900太大而无法转换?

感谢您的帮助!

+1

我不认为'simplejson'用'MustInt64'将json字符串值转换为'int64'。你能提供你正试图解析的json吗? – mkopriva

+0

是的,我找到了原因,你绝对是对的。 – kispi

回答

0

原来的JSON是:

{"created_time":"1505733738"} 

{"created_time":1505733738} 

这原本是一个字符串,而不是数字。

因此,当使用MustInt64()到该json时,它应该返回0,因为type不匹配。

对待这个问题的正确方法是使用strconv。

i64, err := strconv.ParseInt(m.Get("created_time").MustString(), 10, 64) 

你会得到你想要的i64。