英文:
Go nested map iteration
问题
我正在尝试迭代整个eventObj
映射的键,包括其中的嵌套对象,并检查每个键和值以进行进一步的操作。
因此,如果我看到另一个嵌套映射,我也需要对其进行迭代。
我尝试使用类型比较map[string]interface{}
或map[string]interface {}
来实现,但似乎出现了语法错误。
我的问题是如何识别嵌套映射?
(请注意,我可能有多个嵌套映射)
func lookForEmailsInEvent(eventObj map[string]interface {}) {
for key, _ := range eventObj {
valueType := reflect.TypeOf(eventObj[key]).String()
fmt.Printf("%v : %v\n", key, valueType)
if valueType == "map[string]interface {}" {
lookForEmailsInEvent(eventObj[key].(map[string]interface {}))
} else if key == "email" {
// do something...
}
}
}
英文:
I'm trying to iterate over the entire keys of a map eventObj
, including the nested objects inside it and check every key and value for further actions.
So, if I see another nested map I will need to iterate it as well.
I've tried to do so with the comparison of the type to map[string]interface
or map[string]interface{}
but it seems to be a syntax error.
My question is how to identify a nested map?
(note that I can have several nested maps)
func lookForEmailsInEvent(eventObj map[string]interface {}) {
for key, _ := range eventObj {
valueType := reflect.TypeOf(eventObj[key]).String()
fmt.Printf("%v : %v\n", key, valueType)
if valueType == map[string]interface {
lookForEmailsInEvent(eventObj[key])
} else if key == "email" {
// do something...
}
}
}
答案1
得分: 6
以下是如何通过嵌套数据进行递归的方法:
func lookForEmailsInEvent(eventObj map[string]any) {
for k, v := range eventObj {
if v, ok := v.(map[string]any); ok {
lookForEmailsInEvent(v)
} else if k == "email" {
// 做一些操作
}
}
}
这段代码使用了 类型断言 来确定一个值是否为 map[string]any
类型。
英文:
Here's how to recurse through the nested data:
func lookForEmailsInEvent(eventObj map[string]any) {
for k, v := range eventObj {
if v, ok := v.(map[string]any); ok {
lookForEmailsInEvent(v)
} else if k == "email" {
// do something
}
}
}
This code uses a type assertion to determine if a value is a map[string]any
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论