如何解决从文件中读取数据并在Python中转换为JSON
我有以下数据的文件log.txt:
{"__TIMESTAMP":"2020-07-09T19:05:20.858013","__LABEL":"web_channel","__LEVEL":4,"__DIAGNOSE_SLOT":"","msg":"Port web_channel/diagnose_client not connected!"}
{"__TIMESTAMP":"2020-07-09T19:05:21.229737","__LABEL":"context_logging_addon","msg":"startup component"}
{"__TIMESTAMP":"2020-07-09T19:05:21.229761","msg":"activate component"}
{"__TIMESTAMP":"2020-07-09T19:05:21.229793","__LABEL":"context_monitoring_addon","msg":"startup component"}
{"__TIMESTAMP":"2020-07-09T19:05:21.229805","msg":"activate component"}
如果我定义一行,则可以转换为真正的JSON类型:
import json
import datetime
from json import JSONEncoder
log = {
"__TIMESTAMP":"2020-07-09T19:05:21.229737","msg":"Port web_channel/diagnose_client not connected!"}
class DateTimeEncoder(JSONEncoder):
#Override the default method
def default(self,obj):
if isinstance(obj,(datetime.date,datetime.datetime)):
return obj.isoformat()
print("Printing to check how it will look like")
print(DateTimeEncoder().encode(log))
我有以下输出,该格式是完美的JSON。
Printing to check how it will look like
{"__TIMESTAMP": "2020-07-09T19:05:21.229737","__LABEL": "context_logging_addon","__LEVEL": 4,"__DIAGNOSE_SLOT": "","msg": "Port web_channel/diagnose_client not connected!"}
但是我不知道该如何打开log.txt文件,读取数据以将其转换为JSON而不会失败。
能帮我吗?预先感谢。
解决方法
尝试一下:
logs = """[your log file above]"
for log in logs.splitlines():
print(DateTimeEncoder().encode(log))
输出:
"{\"__TIMESTAMP\":\"2020-07-09T19:05:20.858013\",\"__LABEL\":\"web_channel\",\"__LEVEL\":4,\"__DIAGNOSE_SLOT\":\"\",\"msg\":\"Port web_channel/diagnose_client not connected!\"}"
"{\"__TIMESTAMP\":\"2020-07-09T19:05:21.229737\",\"__LABEL\":\"context_logging_addon\",\"msg\":\"startup component\"}"
"{\"__TIMESTAMP\":\"2020-07-09T19:05:21.229761\",\"msg\":\"activate component\"}"
"{\"__TIMESTAMP\":\"2020-07-09T19:05:21.229793\",\"__LABEL\":\"context_monitoring_addon\",\"msg\":\"startup component\"}"
"{\"__TIMESTAMP\":\"2020-07-09T19:05:21.229805\",\"msg\":\"activate component\"}"
,
让我们说您的log.txt文件与.py文件位于同一目录中。
只需使用with open(...
打开它,然后根据语法分析文件即可创建字典列表(每个项目对应一行,然后按照当前操作来分析每个字典)。
这是打开和解析文件的方式:
with open("log.txt","r") as file:
all_text = file.readlines()
parsed_line = list()
for text in all_text:
parsed_line.append(dict([item.split('":"') for item in text[2:-2].split('","')]))
如果您对解析有任何疑问,请告诉我。这很简单。
希望这对您有所帮助。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。