英文:
Golang for loop of certain part of map
问题
尝试为地图的每个部分创建一个for循环。
地图如下所示,我想尝试为ipv4s
中的每个值创建一个for循环。
map[
asn:AS10
time:1.428790768e+09
ipv4s:[
68.114.75.0/24
216.215.56.0/22
216.215.60.0/22]
ipv6s:[
2607:f3f8::/32
]
]
我尝试了以下代码,但显然我做得不正确,因为它仅基于我的php知识:
for json_map["ipv4s"]{
//whatever
}
如果有人需要PHP版本的示例,而不是我试图解释的话,可以参考以下示例:
foreach($obj->ipv4s as $value) {
echo $value; // 返回一个IP地址
}
更新:
package main
import (
"fmt"
"net/http"
"os"
"encoding/json"
)
func main() {
response, err := http.Get("https://www.enjen.net/asn-blocklist/index.php?asn=" + os.Args[1] + "&type=json_split&api=1")
if err != nil {
fmt.Printf("%s", err)
os.Exit(1)
} else {
defer response.Body.Close()
dec := json.NewDecoder(response.Body)
if dec == nil {
panic("Failed to start decoding JSON data")
}
json_map := make(map[string]interface{})
err = dec.Decode(&json_map)
if err != nil {
panic(err)
}
fmt.Printf("%v\n", json_map)
for i := range json_map {
for _, ip := range json_map[i]["ipv4s"] {
fmt.Printf(ip)
}
}
}
}
以上是你要翻译的内容。
英文:
Attempting to create a for loop for each part of a map.
map[
asn:AS10
time:1.428790768e+09
ipv4s:[
68.114.75.0/24
216.215.56.0/22
216.215.60.0/22]
ipv6s:[
2607:f3f8::/32
]]
The above is the map, I'd like to try create a for loop for each value in ipv4s
.
I've attempted, but I'm clearly not doing it correctly as it's merely based off my php knowledge.:
for json_map["ipv4s"]{
//whatever
}
PHP version if anyone needs an example rather then me attempting to explain:
foreach($obj->ipv4s as $value) {
echo $value; // return an ip
}
Update
package main
import (
"fmt"
"net/http"
"os"
"encoding/json"
)
func main() {
response, err := http.Get("https://www.enjen.net/asn-blocklist/index.php?asn=" + os.Args[1] + "&type=json_split&api=1")
if err != nil {
fmt.Printf("%s", err)
os.Exit(1)
} else {
defer response.Body.Close()
dec := json.NewDecoder(response.Body)
if dec == nil {
panic("Failed to start decoding JSON data")
}
json_map := make(map[string]interface{})
err = dec.Decode(&json_map)
if err != nil {
panic(err)
}
fmt.Printf("%v\n", json_map)
for i := range json_map {
for _, ip := range json_map[i]["ipv4s"] {
fmt.Printf(ip)
}
}
}
}
答案1
得分: 3
Effective Go是一个很好的资源,一旦你完成了Go的教程,你可以参考它。在那里也描述了如何迭代一个切片:
for key, value := range json_map {
// ...
}
或者如果你不需要键:
for _, value := range json_map {
// ...
}
如果它是一个切片的映射,你可能需要嵌套两个循环:
for i := range json_map {
for _, ip := range json_map[i]["ipv4s"] {
// ...
}
}
英文:
Effective Go is a good source once you have completed the tutorial for go.
There it is also described how one iterates over a slice:
for key, value := range json_map {
// ...
}
Or if you don't need the key:
for _, value := range json_map {
// ...
}
You might have to nest two loops, if it is a slice of maps:
for i := range json_map {
for _, ip := range json_map[i]["ipv4s"] {
// ...
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论