我正在使用這個JSON 解析器從我從 API 獲得的 JSON 響應中提取數據。它返回一個包含數據的字節數組,當將字節數組轉換為字符串并打印它時,我得到以下輸出: [{"Name": "Vikings", "Type": "show"}, {"Name": "Spartacus: Gods Of The Arena", "Type": "show"}, {"Name": "True Detective", "Type": "show"}, {"Name": "The Borgias", "Type": "show"}, {"Name": "Se7en", "Type": "movie"}]由于這是一個常規字符串,我無法操縱數據來提取我需要的任何內容。理想情況下,我想要這樣的數組: shows := ["Vikings", "Spartacus: Gods Of The Arena"...] movies := ["Se7en", "other data", ...]我想對這些數組做的是根據他/她要求的類型(即:節目、電影等)給用戶標題。所以基本上我正在尋找的是一種將字符串轉換為我可以輕松操作(并且可能過濾)的東西的方法。如果這似乎是一種奇怪的方式,我表示歉意,但我想不出任何其他方式。我覺得 Go 的語法和做事方式與另一種語言(如 Javascript)相比,我可以很容易地在一兩行內完成這項工作。
1 回答

呼如林
TA貢獻1798條經驗 獲得超3個贊
使用標準encoding/json包將數據解組為與數據形狀匹配的值:
var items []struct { // Use slice for JSON array, struct for JSON object
Name string
Type string
}
if err := json.Unmarshal(d, &items); err != nil {
log.Fatal(err)
}
循環遍歷未編組的項目以查找節目和電影:
var shows, movies []string
for _, item := range items {
switch item.Type {
case "movie":
movies = append(movies, item.Name)
case "show":
shows = append(shows, item.Name)
}
}
- 1 回答
- 0 關注
- 146 瀏覽
添加回答
舉報
0/150
提交
取消