You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何递归遍历API返回的任意深度嵌套map并获取最深层键值对

你给出的示例数据结构如下:

data=map[a:map[first_seen:2021-10-20 values:[map[h:<nil> ip:142.250.188.206 ip_count:474360 ip_organization:Google LLC]]] aaaa:map[first_seen:2021-10-20 values:[map[h:<nil> ipv6:2607:f8b0:4004:836::200e ipv6_count:459302 ipv6_organization:<nil>]]] mx:map[first_seen:2021-08-04 values:[map[hostname:aspmx.l.google.com hostname_count:1.3895903e+07 hostname_organization:Google LLC priority:10] map[hostname:alt4.aspmx.l.google.com hostname_count:8.616356e+06 hostname_organization:Google LLC priority:50] map[hostname:alt3.aspmx.l.google.com hostname_count:8.676906e+06 hostname_organization:Google LLC priority:40] map[hostname:alt2.aspmx.l.google.com hostname_count:1.3572714e+07 hostname_organization:Google LLC priority:30] map[hostname:alt1.aspmx.l.google.com hostname_count:1.3653905e+07 hostname_organization:Google LLC priority:20]]] ns:map[first_seen:2021-02-28 values:[map[nameserver:ns4.google.com nameserver_count:5320 nameserver_organization:Google LLC] map[nameserver:ns3.google.com nameserver_count:5328 nameserver_organization:Google LLC] map[nameserver:ns2.google.com nameserver_count:5357 nameserver_organization:Google LLC] map[nameserver:ns1.google.com nameserver_count:5386 nameserver_organization:Google LLC]]] soa:map[first_seen:2021-02-28 values:[map[email:dns-admin.google.com email_count:142373 ttl:900]]] txt:map[first_seen:2021-04-22 values:[map[value:v=spf1 include:_spf.google.com ~all] map[value:google-site-verification=wD8N7i1JTNTkezJ49swvWW48f8_9xveREV4oB-0Hf5o] map[value:google-site-verification=TV9-DBe4R80X4v0M4U_bd_J9cpOJM0nikft0jAgjmsQ] map[value:globalsign-smime-dv=CDYX+XFHUw2wml6/Gb8+59BsH31KzUr6c1l2BPvqKX8=] map[value:facebook-domain-verification=22rm551cu4k0ab0bxsw536tlds4h95] map[value:docusign=1b0a6754-49b1-4db5-8540-d2c12664b289] map[value:docusign=05958488-4752-4ef2-95eb-aa7ba8a3bd0e] map[value:apple-domain-verification=30afIBcvSuDV2PLX] map[value:MS=E4A68B9AB2BB9670BCE15412F62916164C0B20BB]]]]

以下方案基于Go语言实现,核心逻辑可复用至其他语言,仅需调整类型判断、遍历语法即可。

1. 递归遍历任意嵌套map结构

实现思路

通过反射判断当前节点类型,分别处理map、切片/数组、基础值三类节点,支持任意深度穿透:

  • 遇到map类型:遍历所有键值对,对值继续递归
  • 遇到切片/数组类型:遍历所有元素,对元素继续递归
  • 遇到基础类型/ nil:判定为叶子节点,直接输出或处理

代码实现

import (
    "fmt"
    "reflect"
)

// 参数说明:val为当前遍历的值,keyPath为当前节点的键路径(用于定位值的位置)
func TraverseNested(val interface{}, keyPath []string) {
    v := reflect.ValueOf(val)
    // 处理nil值
    if !v.IsValid() {
        fmt.Printf("路径:%v,值:<nil>\n", keyPath)
        return
    }

    switch v.Kind() {
    case reflect.Map:
        // 遍历map所有键值对
        for _, key := range v.MapKeys() {
            newKeyPath := append(keyPath, key.String())
            TraverseNested(v.MapIndex(key).Interface(), newKeyPath)
        }
    case reflect.Slice, reflect.Array:
        // 遍历切片/数组所有元素
        for i := 0; i < v.Len(); i++ {
            newKeyPath := append(keyPath, fmt.Sprintf("[%d]", i))
            TraverseNested(v.Index(i).Interface(), newKeyPath)
        }
    default:
        // 基础类型,输出路径和值
        fmt.Printf("路径:%v,值:%v\n", keyPath, v.Interface())
    }
}

使用示例

// 直接传入你的data变量即可
TraverseNested(data, []string{})
2. 获取最深层map的键与对应值

实现思路

递归遍历时记录当前深度,维护全局变量存储最大深度和对应深度的键值对集合:

  • 遍历到map节点时,比较当前深度和已记录的最大深度:深度更大则清空原有存储更新最大深度,深度相等则追加当前map的键值对
  • 切片默认不算深度层级,可根据需求调整规则

代码实现

import (
    "fmt"
    "reflect"
)

var (
    maxDepth  int
    deepestKV []map[string]interface{}
)

func GetDeepestMapKV(val interface{}, currentDepth int) {
    v := reflect.ValueOf(val)
    if !v.IsValid() {
        return
    }

    switch v.Kind() {
    case reflect.Map:
        // 更新最大深度和对应键值对
        if currentDepth > maxDepth {
            maxDepth = currentDepth
            deepestKV = nil
        }
        if currentDepth == maxDepth {
            currentMap := make(map[string]interface{})
            for _, key := range v.MapKeys() {
                currentMap[key.String()] = v.MapIndex(key).Interface()
            }
            deepestKV = append(deepestKV, currentMap)
        }
        // 继续递归遍历map的值
        for _, key := range v.MapKeys() {
            GetDeepestMapKV(v.MapIndex(key).Interface(), currentDepth+1)
        }
    case reflect.Slice, reflect.Array:
        // 遍历切片元素,深度不变
        for i := 0; i < v.Len(); i++ {
            GetDeepestMapKV(v.Index(i).Interface(), currentDepth)
        }
    }
}

使用示例

// 初始化全局变量
maxDepth = 0
deepestKV = nil
// 传入data,初始深度设为0
GetDeepestMapKV(data, 0)
// 输出结果
fmt.Printf("最大深度:%d\n最深层map键值对:%+v\n", maxDepth, deepestKV)
注意事项
  • 如果需要把切片索引算作深度层级,遍历切片时将currentDepth+1传入即可
  • 若存在多个分支深度相同的最深map,都会被收集到deepestKV中
  • 可自行添加过滤规则,比如跳过值为nil的键值对

内容的提问来源于stack exchange,提问作者chrisxfire

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 04:06:03