Golang循环遍历地图的特定部分

huangapple go评论72阅读模式
英文:

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"] {
      // ...
    }
}

huangapple
  • 本文由 发表于 2015年4月12日 06:33:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/29583841.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定