递归遍历任意数量的嵌套映射

我有一个 API,它返回任意数量的地图,嵌套任意数量的深度。一个例子:

data=map[a:map[first_seen:2021-10-20 values:[map[h:<nil> ip:142.250.188.206 ip_count:474360 ip_organization:Google LLC]]] aaaa:map[first_seen:2021-10-20 values:[map[h:<nil> ipv6:2607:f8b0:4004:836::200e ipv6_count:459302 ipv6_organization:<nil>]]] mx:map[first_seen:2021-08-04 values:[map[hostname:aspmx.l.google.com hostname_count:1.3895903e+07 hostname_organization:Google LLC priority:10] map[hostname:alt4.aspmx.l.google.com hostname_count:8.616356e+06 hostname_organization:Google LLC priority:50] map[hostname:alt3.aspmx.l.google.com hostname_count:8.676906e+06 hostname_organization:Google LLC priority:40] map[hostname:alt2.aspmx.l.google.com hostname_count:1.3572714e+07 hostname_organization:Google LLC priority:30]

如何递归循环通过这样的数据结构?如何在最深层次获得地图的关键价值?


慕盖茨4494581
浏览 87回答 2
2回答

慕容森

像这样的东西应该对你有用——简单的深度优先地图步行者。它在每个叶子节点上调用你的回调函数visit()(“叶子”被定义为“不是地图”),传递它包含路径(指向项目的键)的切片/数组,项目的密钥,以及物品的价值type Visit func( path []interface{}, key interface{}, value interface{} )func MapWalker( data map[interface{}]interface{}, visit Visit ) {&nbsp; traverse( data, []interface{}{}, visit )}func traverse( data map[interface{}]interface{}, path []interface{}, visit Visit ) {&nbsp; for key, value := range data {&nbsp; &nbsp; if child, isMap := value.(map[interface{}]interface{}); isMap {&nbsp; &nbsp; &nbsp; path = append( path, key )&nbsp; &nbsp; &nbsp; traverse( child, path, visit )&nbsp; &nbsp; &nbsp; path = path[:len(path)-1]&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; visit( path, key, child )&nbsp; &nbsp; }&nbsp; }}用法很简单:func do_something_with_item( path []interface{}, key, value interface{} ) {&nbsp; // path is a slice of interface{} (the keys leading to the current object&nbsp; // key is the name of the current property (as an interface{})&nbsp; // value is the current value, agains as an interface{}&nbsp; //&nbsp; // Again it's up to you to cast these interface{} to something usable}MapWalker( someGenericMapOfGenericMaps, do_something_with_item )每次在树中遇到叶节点时,do_something_with_item()都会调用您的函数。

喵喵时光机

如果是 JSON 响应,我有一个包:package mainimport (&nbsp; &nbsp;"fmt"&nbsp; &nbsp;"github.com/89z/parse/json")var data = []byte(`{&nbsp; &nbsp;"soa": {&nbsp; &nbsp; &nbsp; "values":[&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{"email_count":142373, "ttl":900}&nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp;}}`)func main() {&nbsp; &nbsp;var values []struct {&nbsp; &nbsp; &nbsp; Email_Count int&nbsp; &nbsp; &nbsp; TTL int&nbsp; &nbsp;}&nbsp; &nbsp;if err := json.UnmarshalArray(data, &values); err != nil {&nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp;}&nbsp; &nbsp;fmt.Printf("%+v\n", values) // [{Email_Count:142373 TTL:900}]}https://github.com/89z/parse
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go