我想返回一些从API获取的JSON,并在我的Go程序中抛出一个REST端点。数据很好,但不知何故,编码会混淆JSON?
示例代码:
var stockSymbols = []string{
"GOOGL",
"TSLA",
"AAPL",
}
var MarketDataMap = make(map[int]interface{})
func GetStockMarketData() {
for index, stockSymbol := range stockSymbols {
var requestLink = fmt.Sprintf(
"http://somelinkhere/API%sand%v",
stockSymbol, apiKey)
response, err := http.Get(requestLink)
fmt.Println("Getting data for.. " + stockSymbol)
if err != nil {
fmt.Printf("The HTTP request failed with error %s\n", err)
} else {
data, _ := ioutil.ReadAll(response.Body)
MarketDataMap[index] = string(data)
}
}
fmt.Println("recursing...")
time.AfterFunc(time.Second * 10, GetStockMarketData)
}
如果你在这里打印MarketDataMap,它看起来会很好。
然而,当暴露在控制器中时,它完全混乱并在任何地方添加\n
:
func stocksHandler(w http.ResponseWriter, r *http.Request) {
enc := json.NewEncoder(w)
err := enc.Encode(MarketDataMap)
fmt.Println("request made")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// Expose controller at http://localhost:8081/
func StockMarketDataController() {
http.HandleFunc("/stocks", stocksHandler)
log.Fatal(http.ListenAndServe(":8081", nil))
}
显然问题在于编码,我怎样才能避免使用这种方式?
即使是通过JSON插件,数据也是非常难以理解的,例如:
{"0":"{\n \"Meta Data\": {\n \"1. Information\": \"Monthly Prices (open, high, low, close) and Volumes\",\n \"2. Symbol\": \"GOOGL\",\n \"3. Last Refreshed\": \"2018-01-04 14:11:29\",\n \"4. Time Zone\": \"US/Eastern\"\n },\n \"Monthly Time Series\": {\n \"2018-01-04\": {\n
我怎么逃脱所有这些\n
的?它们为什么存在,如何更改控制器以便不创建它们?
看起来http://somelinkhere/
的结果是JSON本身,所以你在Go字符串中有JSON。但是,您尝试再次将JSON字符串编码为stocksHandler
中的JSON,因此您“将JSON嵌套在JSON中”。但是,您尝试编码的对象不是对象,因此任何期望读取真正JSON对象的JSON库都将失败。
如果您在当前响应之后添加{"Data": "
和"}
,那么它将是有效的JSON。只是,它不是返回原始JSON,而是一个带有字符串的JSON对象(该字符串本身就是JSON)。
你要做的是取消从http://somelinkhere/
返回的JSON字符串的代码。所以,而不是这个代码:
data, _ := ioutil.ReadAll(response.Body)
MarketDataMap[index] = string(data)
...你会想要使用the JSON Unmarshal() function,像这样:
rawData, _ := ioutil.ReadAll(response.Body)
data := make(map[string]interface{})
err := json.Unmarshal(rawData, &data)
// Handle err here
MarketDataMap[index] = &data