嵌套地遍历Map

huangapple go评论83阅读模式
英文:

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...
        }
    }
}

这是eventObj的值(从终端截图):
嵌套地遍历Map

英文:

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...
	}
}

}

This is the value of eventObj (screenshot from terminal):
嵌套地遍历Map

答案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 类型。

类型断言的使用方法 可以在 Go 之旅 中找到。

英文:

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.

Type assertions are covered in the Tour of Go.

huangapple
  • 本文由 发表于 2023年1月19日 00:36:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75162435.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定