Generation

generate functionWed, 08 Jan 2025

修改代码import json import re # 配置字符串(多个配置示例) config = """ gtm server /Common/server_yqctv4_ficaos-prod5-vue { datacenter /Common/yq_ct devices { server_yqctv4_ficaos-prod5-vue_1 { addresses { 36.110.52.28 { } } } } monitor /Common/minitor_tcp prober-fallback none prober-pool /Common/prober_yqct prober-preference pool product generic-host virtual-servers { server_yqctv4_ficaos-prod5-vue { destination 36.110.52.28:443 } } } gtm server /Common/server_yqctv4_ficaos-prod6-vue { datacenter /Common/yq_ct devices { server_yqctv4_ficaos-prod6-vue_1 { addresses { 36.110.52.29 { } } } } monitor /Common/minitor_tcp prober-fallback none prober-pool /Common/prober_yqct prober-preference pool product generic-host virtual-servers { server_yqctv4_ficaos-prod6-vue { destination 36.110.52.29:443 } } } """ # 递归解析函数 def parse_recursive(config_str): result = {} lines = config_str.strip().splitlines() stack = [] # 用来存储块 current_key = None current_value = [] for line in lines: line = line.strip() # 跳过空行 if not line: continue print(f"parse_recursive - Processing line: {line}") # 调试输出 # 处理打开大括号的情况 if '{' in line: print(f"parse_recursive - Found opening '{{', entering block") # 调试输出 # 如果当前行包含 '{',则开启新的块 if current_key: # 如果已经有一个当前键,意味着当前值是一个嵌套块 stack.append((current_key, current_value)) current_key = line.split("{")[0].strip() current_value = [] continue # 处理闭合大括号的情况 elif '}' in line: print(f"parse_recursive - Found closing '}}', exiting block") # 调试输出 # 处理闭合的大括号 if stack: # 递归处理嵌套内容 prev_key, prev_value = stack.pop() # 合并嵌套块结果 result[prev_key] = parse_recursive("\n".join(current_value).strip()) if current_value else {} current_key = None current_value = [] continue # 正常的键值对 if current_key: print(f"parse_recursive - Found key-value pair: {current_key} -> {line}") # 调试输出 current_value.append(line) else: # 如果没有打开大括号,说明是普通的键值对 parts = line.split(" ", 1) if len(parts) == 2: print(f"parse_recursive - Found top-level key-value pair: {parts[0]} -> {parts[1]}") # 调试输出 result[parts[0].strip()] = parts[1].strip() return result # 解析外层配置块 def parse_config(config): result = [] # 使用正则表达式,提取所有的 gtm server 配置块 pattern = re.compile(r"(gtm server [^{]+{[^}]+})", re.DOTALL) blocks = pattern.findall(config) print(f"Main parsing - Found {len(blocks)} 'gtm server' blocks") # 调试输出 for block in blocks: outer_key = block.split(" {")[0].strip() inner_config = block.split("{", 1)[1].rsplit("}", 1)[0].strip() print(f"Main parsing - Parsing outer block: {outer_key}") # 调试输出 # 递归解析每个配置块 parsed_inner = parse_recursive(inner_config) result.append({outer_key: parsed_inner}) return result # 调用解析函数 parsed_configs = parse_config(config) # 输出最终的 JSON 格式 json_output = json.dumps(parsed_configs, indent=4) print(f"\nFinal JSON Output:\n{json_output}")

Please keep input under 1000 characters

Questions about programming?Chat with your personal AI assistant