英文:
how to print [][]interface{} in go?
问题
我正在尝试打印来自此页面的数据:https://www.rolimons.com/api/activity
它的样子是这样的:
{"success":true,"activities":[[1624720645,1,6815676017,1080,1047,563399],[1624720637,1,6807138720,915,893,563398],[1624720633,1,6803395856,683,687,563397],[1624720633,1,2409285794,44853,44867,563396],[1624720623,1,71484026,2172,2114,563395],[1624720613,1,9254254,6620,6632,563394],[1624720611,1,124472052,1054,1048,563393],[1624720581,1,6803403781,671,653,563392],[1624720578,1,44113968,972,980,563391],[1624720527,1,332772333,2274,2264,563390]],"activities_count":10}
我使用了https://mholt.github.io/json-to-go/来获取:
type data struct {
Success bool `json:"success"`
Activities [][]interface{} `json:"activities"`
ActivitiesCount int `json:"activities_count"`
}
这是我的代码:
resp, err := http.Get("https://www.rolimons.com/api/activity")
if err != nil {
panic(err)
}
defer resp.Body.Close()
var data *data
error := json.NewDecoder(resp.Body).Decode(&data)
if error != nil {
panic(error)
}
println(data.Activities)
但它给我返回了这个:
[11/13]0xc0002bc000
但我想要它打印出第四个和第五个值,例如:
{"success":true,"activities":[[1624720645,1,6815676017,1080,1047,563399]
应该是:
1080,1047
英文:
i am trying to print the data from this page: https://www.rolimons.com/api/activity
this is how it looks:
{"success":true,"activities":[[1624720645,1,6815676017,1080,1047,563399],[1624720637,1,6807138720,915,893,563398],[1624720633,1,6803395856,683,687,563397],[1624720633,1,2409285794,44853,44867,563396],[1624720623,1,71484026,2172,2114,563395],[1624720613,1,9254254,6620,6632,563394],[1624720611,1,124472052,1054,1048,563393],[1624720581,1,6803403781,671,653,563392],[1624720578,1,44113968,972,980,563391],[1624720527,1,332772333,2274,2264,563390]],"activities_count":10}
i used https://mholt.github.io/json-to-go/
to get:
type data struct {
Success bool `json:"success"`
Activities [][]interface{} `json:"activities"`
ActivitiesCount int `json:"activities_count"`
}
this is my code:
resp, err := http.Get("https://www.rolimons.com/api/activity")
if err != nil {
panic(err)
}
defer resp.Body.Close()
var data *data
error := json.NewDecoder(resp.Body).Decode(&data)
if error != nil {
panic(error)
}
println(data.Activities)
but it gives me this:
[11/13]0xc0002bc000
but i want to make it print the 4th and the 5th value for example:
{"success":true,"activities":[[1624720645,1,6815676017,1080,1047,563399]
would be:
1080,1047
答案1
得分: 4
你可以在这个示例中看到,你可以使用fmt.Printf("%+v\n", data.Activities)
来打印该切片的数据。
要仅打印所需的单元格,可以使用索引来引用它们。
你可以使用方括号[]
来引用切片的索引,例如:data.Activities[0][4]
表示访问第一个嵌套切片的第5个元素。
英文:
As you can see in this example, you can use fmt.Printf("%+v\n", data.Activities)
to print the data of that slice.
To print only the wanted cell, use indices to address them.
You can address slice indices with square braces []
like so:
data.Activities[0][4]
to access the 5th element of the first nested slice.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论