doutuan8887 2018-09-04 07:34
浏览 14
已采纳

在Go中将Json数据解组到地图中

I am dealing with an api that returns json data such as:

    {
  "bpi": {
    "2018-06-01": 128.2597,
    "2018-06-02": 127.3648
  },
  "disclaimer": "something here.",
  "time": {
    "updated": "Sep 6, 2013 00:03:00 UTC",
    "updatedISO": "2013-09-06T00:03:00+00:00"
  }

However the price data that has the accompanying dates can return a dynamic date range (ie could be anything from 1 data pair to 1000).

I'm trying to take only the date and price pairs and put them into a map for later consumption, but I'm not finding a straight forward way of doing it. When I put this into a json-to-go auto struct generator it will create a statically and named struct for the pricing.

This is my best attempt at handling the data dynamically. I am passing an empty interface from the response body of the http get, specifically:

var unstructuredJSON interface{} json.Unmarshal(body, &unstructuredJSON)

and passing the unstructuredJSON to the function:

func buildPriceMap(unstructuredJSON interface{}, priceMap map[string]float64) {
jsonBody := unstructuredJSON.(map[string]interface{})

for k, v := range jsonBody {
    switch vv := v.(type) {
    case string:
        // Do Nothing
    case float64:
        priceMap[k] = vv
    case interface{}:
        buildPriceMap(vv, priceMap)
    default:
        log.Fatal("Json unknown data handling unmarshal error: ", k, vv)
    }
}

Is there a better way to do this?

  • 写回答

1条回答 默认 最新

  • douqin1932 2018-09-04 11:31
    关注

    Assuming that you know the top level keys, e.g. bpi, disclaimer, time etc and that the "dynamic data pairs" that you are talking about are part of the bpi field, and that the key and value types of each of the members of bpi are always string: decimal number you do something like....

    type APIResp struct {
        BPI        map[string]float64 `json:"bpi"`
        Disclaimer string
        // other fields
    }
    

    Now each of your pairs will be typed correctly and contained in the APIResp.BPI map. Unmarshal as you are doing already;

    var r APIResp
    err := json.Unmarshal(body, &r)
    // TODO: check err
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装