提问人:user2497209 提问时间:5/24/2023 最后编辑:Jonathan Halluser2497209 更新时间:5/25/2023 访问量:65
从响应中获取数组中的元素
get element from array from response
问:
我想从HTTP响应的数组中获取第二个元素,但我不明白如何。
// make GET request
response, error := http.Get("https://api.binance.com/api/v3/klines?symbol=ETHUSDT&interval=5m&limit=5")
if error != nil {
fmt.Println(error)
}
// read response body
body, error := ioutil.ReadAll(response.Body)
if error != nil {
fmt.Println(error)
}
// close response body
response.Body.Close()
// print response body
fmt.Println(string(body))
这是责任:
/*
[[1684914900000,"1818.17000000","1818.17000000","1813.82000000","1814.07000000","2252.21430000",1684915199999,
"4088300.51162300",2231,"1056.16450000","1917074.16909000","0"],[1684915200000,"1814.07000000","1816.90000000","1813.35000000",
"1816.76000000","1721.60850000",1684915499999,"3124080.20094500",1984,"1016.47410000","1844514.03018800","0"],
[1684915500000,"1816.76000000","1817.08000000","1815.77000000","1816.66000000","774.00760000",1684915799999,"1405864.36999700",
1349,"382.31660000","694372.58708700","0"],[1684915800000,"1816.67000000","1816.67000000","
1814.43000000","1816.19000000","1390.68620000",1684916099999,"2524716.97451500",1552,"457.95860000","831395.49368900","0"],
[1684916100000,"1816.19000000","1817.08000000","1815.80000000","1817.07000000","536.54530000",1684916399999,"974504.17830700",1047,"312.72070000","568003.96710900","0"]]
*/
我想从第二个数组中获取第二个项目。请帮我解析数组并获取我需要的元素
答:
-1赞
Cetin Basoz
5/24/2023
#1
package main
import (
"encoding/json"
"fmt"
)
func main() {
response := `[[1684914900000,"1818.17000000","1818.17000000","1813.82000000","1814.07000000","2252.21430000",1684915199999,
"4088300.51162300",2231,"1056.16450000","1917074.16909000","0"],[1684915200000,"1814.07000000","1816.90000000","1813.35000000",
"1816.76000000","1721.60850000",1684915499999,"3124080.20094500",1984,"1016.47410000","1844514.03018800","0"],
[1684915500000,"1816.76000000","1817.08000000","1815.77000000","1816.66000000","774.00760000",1684915799999,"1405864.36999700",
1349,"382.31660000","694372.58708700","0"],[1684915800000,"1816.67000000","1816.67000000","1814.43000000","1816.19000000","1390.68620000",1684916099999,"2524716.97451500",1552,"457.95860000","831395.49368900","0"],
[1684916100000,"1816.19000000","1817.08000000","1815.80000000","1817.07000000","536.54530000",1684916399999,"974504.17830700",1047,"312.72070000","568003.96710900","0"]]
`
var elements [][]interface{}
err := json.Unmarshal([]byte(response), &elements)
if err != nil {
fmt.Println(err)
}
fmt.Printf("%v", elements[1][1])
}
1赞
Muhammed Jishin Jamal TCP
5/25/2023
#2
示例项目试用这个。JsonResp 结构,表示 JSON 响应的结构。然后,它发出 HTTP 请求,读取并解析响应正文,并从中提取第二个元素。resp
查看示例项目以更好地理解
评论