Parsing Time from JSON String in GO
Parsing date or time from a JSON String in Go is not as easy it is. Recently i found this problem when i used gin.Context.BindJSON() function to binding a json raw body from client into a struct of mine.
For any other data types, i could easily add “string” on the struct tags. But it does not seem like to be working on time.Time types.
Example:
type MyStruct struct {
Amount float64 `json:"amount,string"`
}
Above type struct will be working smoothly, but for this:
type MyStruct struct {
Date time.Time `json:"time,string"`
}
The parser from BindJSON() always failed to unmarshall the input.
So, i came up with a simple solution.
type MyStruct struct {
Date string `json:"time"`
}
So, instead of telling the BindJSON() to parse the input as a time.Time it simply tell it to just parsing the input as a standard string.
But, did i still get the date format? Yes, of course. This is how
var input MyStruct
if err := context.BindJSON(&input); err != nil {
//doSomething(err)
}
// Parse the input as a time. You can use any format that available. Check time in godoc.org
date, _ := time.Parse("2006-01-02 15:04:05", input.Date)
// do the rest
So, as you can see. When the input came as a string, we could do anything as we need. And i could get the date / time as i need it.
If you have any question or something on your mind, please tell me at [email protected]