doulan1866 2017-10-24 03:16
浏览 28
已采纳

如何在Go中解析其正确类型的JSON值?

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?

  • 写回答

1条回答 默认 最新

  • douzhi9395 2017-10-24 06:37
    关注

    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"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!