Python代码仅输出最后10组VSX数据?排查键重复覆盖问题
问题解决:VS数据批量转JSON仅输出最后一组的问题
问题原因
你的代码只用了单个output_dict字典存储所有键值对,但每组VS的字段(比如VSID、VRID)完全重复,后面遍历到的同名字段会直接覆盖前面的内容,所以最终只剩最后一组VS的数据。
修复方案
改用列表存储多个字典,每遇到空行(两组VS的分隔符)时,就把当前已收集的VS字典加入列表,然后重置临时字典。最后把整个列表转成JSON输出。
修复后的代码
import json show_vs = [ 'VSID: 0 ', 'VRID: 0 ', 'Type: VSX Gateway', 'Name: chckpt-fw1a', 'Security Policy: VS-policy', 'Installed at: 12Jan2023 21:57:15', 'SIC Status: Trust', 'Connections number: 52', 'Connections peak: 152', 'Connections limit: 14900', 'VSID: 1 ', 'VRID: 1 ', 'Type: VSX Gateway', 'Name: chckpt-fw1a', 'Security Policy: VS-policy', 'Installed at: 12Jan2023 21:57:15', 'SIC Status: Trust', 'Connections number: 52', 'Connections peak: 152', 'Connections limit: 14900', 'VSID: 2 ', 'VRID: 2 ', 'Type: VSX Gateway', 'Name: chckpt-fw1a', 'Security Policy: VS-policy', 'Installed at: 12Jan2023 21:57:15', 'SIC Status: Trust', 'Connections number: 52', 'Connections peak: 152', 'Connections limit: 14900', ] output_list = [] current_vs = {} for item in show_vs: # 处理空行:如果当前VS有数据,就加入列表并重置 if not item.strip(): if current_vs: output_list.append(current_vs) current_vs = {} continue splitted = item.split(": ") if len(splitted) <= 1: continue current_vs[splitted[0].strip()] = splitted[1].strip() # 把最后一组VS加入列表 if current_vs: output_list.append(current_vs) jsn = json.dumps(output_list, indent=4) print(jsn)
输出效果
会生成包含3个VS字典的JSON数组,每个字典对应一组VS的完整数据,不会再出现字段覆盖问题。
内容的提问来源于stack exchange,提问作者Kumar
相关产品推荐
相关产品推荐

