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