亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

遞歸遍歷任意數量的嵌套映射

遞歸遍歷任意數量的嵌套映射

Go
慕蓋茨4494581 2022-10-10 10:29:42
我有一個 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]如何遞歸循環通過這樣的數據結構?如何在最深層次獲得地圖的關鍵價值?
查看完整描述

2 回答

?
慕容森

TA貢獻1853條經驗 獲得超18個贊

像這樣的東西應該對你有用——簡單的深度優先地圖步行者。它在每個葉子節點上調用你的回調函數visit()(“葉子”被定義為“不是地圖”),傳遞它

  • 包含路徑(指向項目的鍵)的切片/數組,

  • 項目的密鑰,以及

  • 物品的價值

type Visit func( path []interface{}, key interface{}, value interface{} )


func MapWalker( data map[interface{}]interface{}, visit Visit ) {

  traverse( data, []interface{}{}, visit )

}


func traverse( data map[interface{}]interface{}, path []interface{}, visit Visit ) {


  for key, value := range data {


    if child, isMap := value.(map[interface{}]interface{}); isMap {


      path = append( path, key )

      traverse( child, path, visit )

      path = path[:len(path)-1]


    } else {


      visit( path, key, child )


    }


  }


}

用法很簡單:



func do_something_with_item( path []interface{}, key, value interface{} ) {

  // path is a slice of interface{} (the keys leading to the current object

  // key is the name of the current property (as an interface{})

  // value is the current value, agains as an interface{}

  //

  // Again it's up to you to cast these interface{} to something usable

}


MapWalker( someGenericMapOfGenericMaps, do_something_with_item )

每次在樹中遇到葉節點時,do_something_with_item()都會調用您的函數。


查看完整回答
反對 回復 2022-10-10
?
喵喵時光機

TA貢獻1846條經驗 獲得超7個贊

如果是 JSON 響應,我有一個包:


package main


import (

   "fmt"

   "github.com/89z/parse/json"

)


var data = []byte(`

{

   "soa": {

      "values":[

         {"email_count":142373, "ttl":900}

      ]

   }

}

`)


func main() {

   var values []struct {

      Email_Count int

      TTL int

   }

   if err := json.UnmarshalArray(data, &values); err != nil {

      panic(err)

   }

   fmt.Printf("%+v\n", values) // [{Email_Count:142373 TTL:900}]

}

https://github.com/89z/parse


查看完整回答
反對 回復 2022-10-10
  • 2 回答
  • 0 關注
  • 104 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號