如何将来自https://api.twitchinsights.net/v1/bots/online的 JSON 响应解析为Go 中的数组并遍历每个条目?
我不明白结构,因为没有键只有值......
任何人都可以请帮助并解释这是如何工作的吗?
我已经映射了它,但后来我得到了类似的东西
map[_total:216 bots:[[anotherttvviewer 67063 1.632071051e+09] [defb 26097 1.632071051e+09] [commanderroot 17531 1.632071048e+09] [apparentlyher 16774 1.63207105e+09]...
但我无法遍历地图。
因为您使用的 API 返回的数据可能是字符串或数字(在数组属性数组中bots
),所以您需要使用[]interface{}
该数组的每个元素的类型,因为空接口 ( https: //tour.golang.org/methods/14 ) 在运行时适用于任何类型。
type response struct {
Bots [][]interface{} `json:"bots"`
Total int `json:"_total"`
}
然后,当您遍历切片中的每个项目时,您可以使用反射检查其类型。
API 以模式返回数据是理想的,其中每个 JSON 数组元素与其数组中的每个其他元素都具有相同的 JSON 类型。这将更容易解析,尤其是使用像 Go 这样的静态类型语言。
例如,API 可以返回如下数据:
{
"bots": [
{
"stringProp": "value1",
"numberProps": [
1,
2
]
}
],
"_total": 1
}
然后,您可以编写一个表示 API 响应的结构,而无需使用空接口:
type bot struct {
StringProp string `json:"stringProp"`
NumberProps []float64 `json:"numberProps"`
}
type response struct {
Bots []bot `json:"bots"`
Total int `json:"_total"`
}
但有时您无法控制正在使用的 API,因此您需要愿意以更动态的方式解析响应中的数据。如果您确实可以控制 API,则应考虑以这种方式返回数据。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句