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

如何在Python中解析Golang打印输出的map字符串?

解析Go风格Map字符串为Python字典

要将Go打印输出的map格式字符串转换为Python字典,可以通过编写递归解析函数实现,支持嵌套map、列表以及带引号的字符串元素。

核心实现代码

def strip_quotes(s):
    """去除字符串首尾的引号(单/双引号)"""
    if (s.startswith('"') and s.endswith('"')) or (s.startswith("'") and s.endswith("'")):
        return s[1:-1]
    return s

def split_with_brackets(s, sep=' '):
    """考虑括号和引号的字符串分割,避免分割嵌套结构内部的分隔符"""
    parts = []
    current = []
    bracket_depth = 0
    in_quote = False
    quote_char = None
    
    for c in s:
        # 处理引号包裹的内容
        if (c == '"' or c == "'") and not in_quote:
            in_quote = True
            quote_char = c
        elif c == quote_char and in_quote:
            in_quote = False
        # 处理括号嵌套
        elif not in_quote:
            if c == '[':
                bracket_depth += 1
            elif c == ']':
                bracket_depth -= 1
            # 仅在括号深度为0且不在引号内时,按分隔符分割
            elif c == sep and bracket_depth == 0:
                parts.append(''.join(current))
                current = []
                continue
        current.append(c)
    
    if current:
        parts.append(''.join(current))
    return parts

def parse_go_map(go_map_str):
    """解析Go风格的map字符串为Python字典"""
    # 处理空map情况
    if go_map_str.strip() == 'map[]':
        return {}
    
    # 去除外层的map[和]
    content = go_map_str[4:-1].strip()
    if not content:
        return {}
    
    # 分割键值对(考虑嵌套结构)
    kv_pairs = split_with_brackets(content)
    result = {}
    
    for pair in kv_pairs:
        # 分割键和值(按第一个冒号分割)
        key, value = pair.split(':', 1)
        key = key.strip()
        value = value.strip()
        
        # 递归处理嵌套的map
        if value.startswith('map[') and value.endswith(']'):
            result[key] = parse_go_map(value)
        # 处理列表类型的值
        elif value.startswith('[') and value.endswith(']'):
            list_content = value[1:-1].strip()
            if not list_content:
                result[key] = []
            else:
                # 分割列表元素并去除引号
                result[key] = [strip_quotes(item) for item in split_with_brackets(list_content)]
        # 处理普通字符串/数值类型的值
        else:
            result[key] = strip_quotes(value)
    
    return result

使用示例

# 基础示例
go_map = 'map[customer_ids:[Test1 Test2]]'
print(parse_go_map(go_map))
# 输出: {'customer_ids': ['Test1', 'Test2']}

# 多键值对+带引号元素
go_map2 = 'map[name:"Bob Smith" age:30 tags:[work "personal projects"]]'
print(parse_go_map(go_map2))
# 输出: {'name': 'Bob Smith', 'age': '30', 'tags': ['work', 'personal projects']}

# 嵌套map
go_map3 = 'map[data:map[username:alice role:admin] settings:[notifications enabled]]'
print(parse_go_map(go_map3))
# 输出: {'data': {'username': 'alice', 'role': 'admin'}, 'settings': ['notifications', 'enabled']}

注意事项

  • 该实现假设Go打印的map中,字符串元素若包含空格会被引号包裹(Go默认行为),函数会自动去除首尾引号。
  • 若需要将数值类型的字符串转换为Python的int/float,可以在处理普通值时添加类型转换逻辑,比如尝试用int()或float()转换,失败则保留字符串。
  • 对于更复杂的Go类型(如结构体),需要扩展解析逻辑,但基础的map、列表、字符串/数值类型都能覆盖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 23:05:26