如何解析多条目JSON文件并生成IP:Port格式的文本文件
这问题我经常遇到,给你两种实用的解决方案,你可以根据自己的操作习惯和环境来选:
解决方案1:Python脚本(通用跨平台)
这个方法适合所有操作系统,还能灵活处理各种边缘情况(比如每个IP对应多个端口、文件里有无效JSON内容等)。
步骤说明:
- 读取原文件内容,用JSON解码器逐个解析连续的JSON对象(你的示例里两个JSON是直接拼接的,不是数组,所以需要这种逐个解析的方式)
- 提取每个对象里的
ip和ports数组中的端口号 - 将
ip:port格式的字符串写入新文件
完整代码:
import json def extract_ip_port(input_file, output_file): # 读取原始文件内容 with open(input_file, 'r', encoding='utf-8') as f: raw_content = f.read() decoder = json.JSONDecoder() current_pos = 0 result_lines = [] # 循环解析每一个JSON对象 while current_pos < len(raw_content): try: # 解码当前位置的JSON对象,返回对象和下一个对象的起始位置 json_obj, current_pos = decoder.raw_decode(raw_content, current_pos) # 获取IP地址 ip_address = json_obj.get('ip') if not ip_address: current_pos += 1 continue # 遍历ports数组,提取每个端口(支持一个IP对应多个端口的情况) for port_item in json_obj.get('ports', []): port_number = port_item.get('port') if port_number is not None: result_lines.append(f"{ip_address}:{port_number}") except json.JSONDecodeError: # 遇到无效内容时,跳过一个字符继续解析 current_pos += 1 # 将结果写入输出文件 with open(output_file, 'w', encoding='utf-8') as f: f.write('\n'.join(result_lines)) # 替换成你的输入输出文件路径 extract_ip_port('your_input_file.txt', 'your_output_file.txt')
使用方法:
把上面的代码保存为parse_ip_port.py,替换代码里的文件路径,然后运行python parse_ip_port.py即可。
解决方案2:命令行工具jq(适合Linux/macOS快速处理)
如果你熟悉命令行,用jq工具会更高效,不需要写脚本。不过首先需要把你的原始文件调整为每行一个JSON对象的格式(也就是JSON Lines格式)。
步骤1:格式化原始文件(分割连续的JSON)
如果你的原始文件里JSON是直接拼接的(像示例那样),先用sed命令分割成每行一个:
sed 's/{"ip"/\n{"ip"/g' your_input_file.txt > formatted.json
这个命令会在每个{"ip"前面加换行符,把连续的JSON拆成单独一行的格式。
步骤2:提取IP和端口
- 如果每个IP只对应一个端口(像你的示例),用这个命令:
jq -r '.ip + ":" + (.ports[0].port | tostring)' formatted.json > output.txt
- 如果每个IP可能对应多个端口,需要全部提取的话,用这个:
jq -r '.ip as $ip | .ports[] | $ip + ":" + (.port | tostring)' formatted.json > output.txt
说明:
jq是Linux/macOS常用的JSON处理工具,大部分系统默认安装,如果没有的话可以用包管理器安装(比如apt install jq或者brew install jq)。
内容的提问来源于stack exchange,提问作者user2689877
相关产品推荐
相关产品推荐

