I'm processing events from an JSON API in Go but unfortunately every value returned is encapsulated as string.
The JSON events coming form that API look somewhat as the following:
[
{
"id": "283702",
"price": "59.99",
"time": "1508813904",
"type": "some_update"
},
{
"id": "283701",
"price": "17.50",
"time": "1508813858",
"type": "some_update"
}
]
Now my code to parse these evens looks like the following example:
type event []struct {
ID string `json:"id"`
Price string `json:"price"`
Time string `json:"time"`
Type string `json:"type"`
}
// Requesting and parsing events here ...
id, err := strconv.ParseInt(event.ID, 0, 64)
if err != nil {
return err
}
price, err := strconv.ParseFloat(event.Price, 64)
if err != nil {
return err
}
timestamp, err := strconv.ParseInt(event.Time, 0, 64)
if err != nil {
return err
}
datetime := time.Unix(timestamp, 0).UTC()
Now this code is a bit repetitive but basically I'm parsing the id
, price
and time
and then I'm converting the timestamp to a time value.
Now my question, can I convert the values at the same time as parsing the JSON response? Or is there no way around this and I need to do the type conversion later as shown in this example?