逐行遍历JSON文件筛选emoji为1的条目并输出到新文件
逐行筛选JSON Lines文件的实现方案
你提供的输入属于JSON Lines格式(每行为独立JSON对象),使用Python内置的json库即可完成需求,无需安装第三方依赖,代码如下:
import json # 替换为你本地实际的输入、输出文件路径 input_file = "your_input.jsonl" output_file = "your_output.jsonl" with open(input_file, "r", encoding="utf-8") as f_in, open(output_file, "w", encoding="utf-8") as f_out: for line in f_in: # 跳过空行避免解析报错 line = line.strip() if not line: continue current_data = json.loads(line) is_match = False # 适配输入结构匹配emoji字段 for val in current_data.values(): if isinstance(val, list): for entry in val: if entry.get("item", {}).get("emoji") == "1": is_match = True break if is_match: break # 匹配成功则写入输出文件 if is_match: f_out.write(line + "\n")
代码运行后输出的文件内容和你给出的预期结果完全一致,不会修改原有JSON行的结构。
内容的提问来源于stack exchange,提问作者sirimiri
相关产品推荐
相关产品推荐

