2 回答

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超18個(gè)贊
像這樣的東西應(yīng)該對(duì)你有用——簡(jiǎn)單的深度優(yōu)先地圖步行者。它在每個(gè)葉子節(jié)點(diǎn)上調(diào)用你的回調(diào)函數(shù)visit()
(“葉子”被定義為“不是地圖”),傳遞它
包含路徑(指向項(xiàng)目的鍵)的切片/數(shù)組,
項(xiàng)目的密鑰,以及
物品的價(jià)值
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 )
}
}
}
用法很簡(jiǎn)單:
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 )
每次在樹(shù)中遇到葉節(jié)點(diǎn)時(shí),do_something_with_item()都會(huì)調(diào)用您的函數(shù)。

TA貢獻(xiàn)1846條經(jīng)驗(yàn) 獲得超7個(gè)贊
如果是 JSON 響應(yīng),我有一個(gè)包:
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 關(guān)注
- 113 瀏覽
添加回答
舉報(bào)