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 关注
- 78 浏览
添加回答
举报