go - Go - 遍历嵌套结构
问题描述
我有这种复杂的结构:
type InFoo struct {
v3 int
}
type Bar struct {
v1 int
v2 InFoo
}
type Foo struct {
A int
B string
C Bar
}
在运行时,这可以进一步深入嵌套。我在下面编写了一个函数来遍历以下字段:
func main() {
f := Foo{A: 10, B: "Salutations", C: Bar{v1: 10, v2: InFoo{v3: 20}}}
fType := reflect.TypeOf(f)
newexaminer(fType)
}
// recursive traversal
func newexaminer(t reflect.Type) {
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
fmt.Println(f.Name, f.Type.Kind(), f.Type)
if f.Type.Kind() == reflect.Struct {
// recurse if struct
newexaminer(f.Type)
}
}
}
虽然这可行,但我不确定是否有更好/优化的方法来做到这一点。请建议!
- 编辑:1根据评论,我将方法更改为:
func main() {
f := Foo{A: 10, B: "Salutations", C: Bar{v1: 10, v2: InFoo{v3: 20}}}
jsonRes, err := json.Marshal(f)
if err != nil {
fmt.Println(err)
}
var iRes interface{}
err = json.Unmarshal(jsonRes, &iRes)
if err != nil {
fmt.Println(err)
}
res := iRes.(map[string]interface{})
for _, v := range res {
fmt.Println(v)
// need to type assert v again to extract map keys/values
}
}
游乐场: https: //play.golang.org/p/_TXrRGxpIyx
这是遍历结构的惯用方式吗?看起来这仍然需要多个断言和循环才能到达最内部的字段。这是解析复杂 json 文档的理想方法还是有更好的方法来做到这一点
解决方案
推荐阅读
- python - 链接 python app docker 和 postgress docker
- excel - How to Fix Graphs not copying over to new sheet with PasteSpecial
- db2 - IBM DB/2 i - SQL 从 Json_Table 中选择 JSON_VAL"
- reactjs - 动作被触发,但存储值未更新
- javascript - How to short Timing Array Data with From and To keys
- angular - Angular 7 Cli does not applies angular.json schematics options in Ionic 4 project
- amazon-web-services - What is the difference between Amazon managed Blockchain and Amazon Blockchain Templates?
- android - 如何在网格回收器视图中创建加号图标以添加图像?
- php - PHP set_time_limit() 的作用域是什么?
- sql-server - 如何使用动态查询获取表中的列数