如何通过Node.js读取TXT文件并转换为指定JSON格式?
解决方案
可以用Python实现这个格式转换,具体步骤和代码如下:
实现思路
- 读取目标TXT文件的所有内容,按行拆分
- 对每一行按逗号分割字段,提取ID、操作类型(CheckIn/CheckOut)和时间戳
- 根据操作类型构建对应结构的字典,最后将所有字典组合成数组并转为JSON格式
示例代码
import json # 替换为你的TXT文件路径 file_path = "your_records.txt" result_list = [] with open(file_path, "r", encoding="utf-8") as f: # 按行读取并过滤空行 for line in f.read().splitlines(): if not line.strip(): continue # 分割每行的字段 fields = line.split(",") # 确保字段数量正确,避免报错 if len(fields) != 5: continue user_id = fields[0] action_type = fields[3] time_str = fields[4] # 根据操作类型生成对应结构的字典 if action_type == "CheckIn": result_list.append({"id": user_id, "checkIn": time_str}) elif action_type == "CheckOut": result_list.append({"id": user_id, "checkOut": time_str}) # 转换为格式化的JSON字符串 final_json = json.dumps(result_list, indent=2) print(final_json)
针对你提供的TXT内容,运行后输出如下
[ { "id": "1000", "checkIn": "19.01.2023 20:18" }, { "id": "1002", "checkIn": "19.01.2023 20:18" }, { "id": "1000", "checkOut": "19.01.2023 20:18" } ]
额外说明
- 代码会自动跳过空行和格式不正确的行,避免运行报错
- 如果需要统一时间格式(比如补全秒数),可以在处理
time_str时添加时间格式化逻辑
内容的提问来源于stack exchange,提问作者arda alcinkaya
相关产品推荐
相关产品推荐

