从文件中读取数据并在Python中转换为JSON

时间:2020-08-19 21:40:42

标签: json python-3.x parsing

我有以下数据的文件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","__LEVEL":4,"__DIAGNOSE_SLOT":"","msg":"startup component"}
{"__TIMESTAMP":"2020-07-09T19:05:21.229761","__LABEL":"context_logging_addon","__LEVEL":4,"__DIAGNOSE_SLOT":"","msg":"activate component"}
{"__TIMESTAMP":"2020-07-09T19:05:21.229793","__LABEL":"context_monitoring_addon","__LEVEL":4,"__DIAGNOSE_SLOT":"","msg":"startup component"}
{"__TIMESTAMP":"2020-07-09T19:05:21.229805","__LABEL":"context_monitoring_addon","__LEVEL":4,"__DIAGNOSE_SLOT":"","msg":"activate component"}

如果我定义一行,则可以转换为真正的JSON类型:

import json
import datetime
from json import JSONEncoder

log = {
    "__TIMESTAMP":"2020-07-09T19:05:21.229737",
    "__LABEL":"context_logging_addon",
    "__LEVEL":4,
    "__DIAGNOSE_SLOT":"",
    "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而不会失败。

能帮我吗?预先感谢。

2 个答案:

答案 0 :(得分:0)

尝试一下:

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\",\"__LEVEL\":4,\"__DIAGNOSE_SLOT\":\"\",\"msg\":\"startup component\"}"
   "{\"__TIMESTAMP\":\"2020-07-09T19:05:21.229761\",\"__LABEL\":\"context_logging_addon\",\"__LEVEL\":4,\"__DIAGNOSE_SLOT\":\"\",\"msg\":\"activate component\"}"
"{\"__TIMESTAMP\":\"2020-07-09T19:05:21.229793\",\"__LABEL\":\"context_monitoring_addon\",\"__LEVEL\":4,\"__DIAGNOSE_SLOT\":\"\",\"msg\":\"startup component\"}"
"{\"__TIMESTAMP\":\"2020-07-09T19:05:21.229805\",\"__LABEL\":\"context_monitoring_addon\",\"__LEVEL\":4,\"__DIAGNOSE_SLOT\":\"\",\"msg\":\"activate component\"}"

答案 1 :(得分:0)

让我们说您的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('","')]))

如果您对解析有任何疑问,请告诉我。这很简单。

希望这对您有所帮助。

相关问题