Martin
Martin

Reputation: 43

How to parse JSON values in its correct type in Go?

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?

Upvotes: 3

Views: 106

Answers (1)

ANisus
ANisus

Reputation: 77925

You don't have to use string type. The encoding/json package can handle the conversion from string to string, floating point, integer, or boolean types by using the "string" option in the tags.

As an example, try:

type event []struct {
    ID    uint64  `json:"id,string"`
    Price float64 `json:"price,string"`
    Time  int64   `json:"time,string"`
    Type  string  `json:"type"`
}

Upvotes: 6

Related Questions