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()都會調用您的函數。

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
- 2 回答
- 0 關注
- 104 瀏覽
添加回答
舉報