我正在處理一個(gè)返回 json 數(shù)據(jù)的 api,例如: { "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" }然而,具有伴隨日期的價(jià)格數(shù)據(jù)可以返回動(dòng)態(tài)日期范圍(即可以是從 1 個(gè)數(shù)據(jù)對(duì)到 1000 個(gè)數(shù)據(jù)對(duì)的任何值)。我試圖只獲取日期和價(jià)格對(duì)并將它們放入地圖中供以后使用,但我沒(méi)有找到一種直接的方法。當(dāng)我將它放入一個(gè) json-to-go 自動(dòng)結(jié)構(gòu)生成器中時(shí),它將為定價(jià)創(chuàng)建一個(gè)靜態(tài)的命名結(jié)構(gòu)。這是我動(dòng)態(tài)處理數(shù)據(jù)的最佳嘗試。我從 http get 的響應(yīng)主體傳遞一個(gè)空接口,具體來(lái)說(shuō):var unstructuredJSON interface{} json.Unmarshal(body, &unstructuredJSON)并將 unstructuredJSON 傳遞給函數(shù):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) }}有一個(gè)更好的方法嗎?
在 Go 中將 Json 數(shù)據(jù)解組到地圖中
慕蓋茨4494581
2023-03-29 16:10:17