如何在Go+Beego框架中解析URL返回的JSON并提取时间序列数据
Solution for Extracting and Restructuring Time Series Data in Beego/Go
Got it, let's get this sorted. Your current code fetches the data but doesn't properly extract and restructure the "Time Series (1min)" data as you need. Here's a revised version that does exactly what you're asking for, with clear explanations along the way:
Step-by-Step Revised Code
func (d *Tom) Get() { // Fetch the time series data from Alpha Vantage resp, err := http.Get("https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=KLMH2VF0LCFNOX5") if err != nil { panic(err) // Note: In production, replace with graceful error handling like d.Abort(500, err.Error()) } defer resp.Body.Close() // Decode the JSON response into a generic map dec := json.NewDecoder(resp.Body) jsonMap := make(map[string]interface{}) if err := dec.Decode(&jsonMap); err != nil { panic(err) // Again, handle this gracefully in production code } // Extract the "Time Series (1min)" field with type safety checks timeSeriesRaw, ok := jsonMap["Time Series (1min)"] if !ok { panic("Could not find 'Time Series (1min)' in the response") } timeSeries, ok := timeSeriesRaw.(map[string]interface{}) if !ok { panic("'Time Series (1min)' data is not in the expected map format") } // Option 1: Restructure data with clean field names (remove number prefixes) cleanedTimeSeries := make(map[string]map[string]string) for timestamp, rawData := range timeSeries { priceData, ok := rawData.(map[string]interface{}) if !ok { continue // Skip invalid entries if any } // Map the numbered keys to cleaner, more readable ones cleanedEntry := map[string]string{ "open": priceData["1. open"].(string), "high": priceData["2. high"].(string), "low": priceData["3. low"].(string), "close": priceData["4. close"].(string), "volume": priceData["5. volume"].(string), } cleanedTimeSeries[timestamp] = cleanedEntry } // Option 2: Convert to an array of objects (if you prefer this format over timestamp keys) // var timeSeriesArray []map[string]interface{} // for timestamp, rawData := range timeSeries { // priceData := rawData.(map[string]interface{}) // entry := map[string]interface{}{ // "timestamp": timestamp, // "open": priceData["1. open"], // "high": priceData["2. high"], // "low": priceData["3. low"], // "close": priceData["4. close"], // "volume": priceData["5. volume"], // } // timeSeriesArray = append(timeSeriesArray, entry) // } // Return the restructured data as JSON d.Data["json"] = cleanedTimeSeries // Swap with timeSeriesArray if you chose Option 2 d.ServeJSON() }
Key Improvements & Explanations:
- Fixed Error Handling: Moved the
Decodeerror check right after decoding, so we catch issues before trying to process the data. No more checking errors after looping through invalid data! - Type Safety: Used type assertions to safely access nested map values—this prevents unexpected runtime panics if the API response structure changes slightly.
- Cleaner Output: Added two options for restructuring the data: one that keeps timestamps as keys (with cleaned field names) and another that converts everything into an array of objects, depending on what your frontend needs.
- Production Readiness: Added notes about replacing
panic()with proper HTTP error responses for real-world use.
Example Cleaned Response (Timestamp Key Format):
{ "2018-05-24 14:23:00": { "open": "98.1432", "high": "98.1661", "low": "98.1238", "close": "98.1500", "volume": "19106" }, "2018-05-24 14:24:00": { "open": "98.1500", "high": "98.1700", "low": "98.1400", "close": "98.1650", "volume": "18279" } }
内容的提问来源于stack exchange,提问作者MWA
相关产品推荐
相关产品推荐

