python - Python:将文本文件解析为格式化的 json 文件
问题描述
我有一个文本文件,需要提取一些信息并以格式化的方式将其写入 JSON 文件。
文本文件:
Jul 23 06:43:06 localhost : [file.download][Informational][0X1013] Attempting connection to https://fileserver/file/abcdefg
Jul 23 06:43:06 localhost : [file.download][Informational][0X800F0000] CA file error
必需的 JSON 格式化方式:
{'Timestamp': 'Jul 23 06:43:06 ', 'Source': 'file.download', 'Level': 'Informational', 'code': '0X1013', 'messages': 'Attempting connection to https://fileserver/file/abcdefg'}
{'Timestamp': 'Jul 23 06:43:06 ', 'Source': 'file.download', 'Level': 'Informational', 'code': '0X800F0000', 'messages': 'CA file error'}
代码:
import json
with open('c:\Temp\log.txt', 'r') as data:
result = [ {
'Timestamp': line.strip().split('localhost : ')[0],
'Source': line.strip().split('[')[1].rstrip(']'),
'Level': line.strip().split('[')[2].rstrip(']'),
'code': line.strip().split('[')[3].split(']')[0],
'messages': line.strip().split('[')[3].split(']')[1].strip()
} for line in data]
print(result)
with open('output.json', 'w') as json_file:
json_file.write(json.dumps(result))
输出:
[{'Timestamp': 'Jul 23 06:43:06 ', 'Source': 'file.download', 'Level': 'Informational', 'code': '0X1013', 'messages': 'Attempting connection to https://fileserver/file/abcdefg'}, {'Timestamp': 'Jul 23 06:43:06 ', 'Source': 'file.download', 'Level': 'Informational', 'code': '0X800F0000', 'messages': 'CA file error'}]
问题:
为了使代码输出与“必需的 JSON 格式方式”相同,我必须做什么?
解决方案
认为这可行(来自Dump two dictionary in a json file on separate lines 的帮助)
import json
with open('c:\Temp\log.txt', 'r') as data:
result = [ {
'Timestamp': line.strip().split('localhost : ')[0],
'Source': line.strip().split('[')[1].rstrip(']'),
'Level': line.strip().split('[')[2].rstrip(']'),
'code': line.strip().split('[')[3].split(']')[0],
'messages': line.strip().split('[')[3].split(']')[1].strip()
} for line in data]
with open('output.json', 'w') as json_file:
json.dump(result[0], json_file)
json_file.write('\n')
json.dump(result[1], json_file)
推荐阅读
- c++ - 非平凡可复制类型的 C++ 值表示
- sql - 如何在 bigquery 窗口中查找分类异常值/噪声行
- python - pdoc3-ValueError:找不到文件或模块
- python - 如何从字符串创建图像?
- python - Django Rest Framework 嵌套可写字段 mixins drf_writable_nested
- python - 获取所采用的路径,直到 python 中的一行
- r - 在 r data.table 中添加列
- javascript - 在javascript中合并动态对象数组
- jenkins - 满足条件时对整个管道使用特殊代理
- spring-boot - Spring Boot 服务器和客户端测试。是否有可能将它们结合起来实现这样的目标?