[英]converting txt data (from log file) into json using python?
我有一個日志文件,其格式如下所示:
parsed: {'priority': '14', 'timestamp': '2021-04-13 13:42:07', 'hostname': 'invi-dev-gw2', 'rootname': 'root', 'pid': '27889', 'message': 'Session STARTED - Client[ID:8242, Physical: 111.119.187.47, Virtual: 10.1.0.66] <--> Service[Name:Attendance1, ID:704, Physical: 192.168.3.18, Virtual: 10.1.0.67]'}
parsed: {'priority': '15', 'timestamp': '2021-04-13 13:42:07', 'hostname': 'invi-dev-gw3', 'rootname': 'root', 'pid': '27890', 'message': 'Session STOPPED - Client[ID:8242, Physical: 111.119.187.47, Virtual: 10.1.0.66] <--> Service[Name:Attendance1, ID:704, Physical: 192.168.3.18, Virtual: 10.1.0.67]'}
文本文件中基本上有兩個數據。 下一步是使用 Python 將文本數據轉換為 JSON。到目前為止,我有用於 JSON 轉換的 python 腳本,如下所示:
# Python program to convert text
# file to JSON
import json
# the file to be converted to
# json format
filename = 'output.txt'
# dictionary where the lines from
# text will be stored
dict1 = {}
# creating dictionary
with open(filename) as fh:
for line in fh:
# reads each line and trims of extra the spaces
# and gives only the valid words
command, description = line.strip().split(None, 1)
dict1[command] = description.strip()
# creating json file
# the JSON file is named as test1
out_file = open("test.json", "w")
json.dump(dict1, out_file, indent = 4, sort_keys = False)
out_file.close()
現在創建了 JSON 文件,但它只顯示了一個數據(output 應該顯示 2 個數據),如下所示:
"parsed:": "{'priority': '15',
'timestamp': '2021-04-13 13:42:07',
'hostname': 'invi-dev-gw3',
'rootname': 'root',
'pid': '27890',
'message': 'Session STOPPED - Client[ID:8242, Physical: 111.119.187.47, Virtual: 10.1.0.66] <--> Service[Name:Attendance1, ID:704, Physical: 192.168.3.18, Virtual: 10.1.0.67]'
}"
我不知道為什么它不打印整個數據。 它應該顯示 JSON 文件中的另一個數據,但只顯示了一個。 誰能幫我這個?
你有dict1[command] = description.strip()
你真的想要更像的東西: dict1[command].append(description.strip())
(所以dict1
真的想成為一個列表)。 還有一個問題是您可能想使用json.loads()
但您的輸入數據使用單引號所以讓我們用ast
解析它
我會嘗試類似的東西:
import ast
import collections
import json
data_in = [
"parsed: {'priority': '14', 'timestamp': '2021-04-13 13:42:07', 'hostname': 'invi-dev-gw2', 'rootname': 'root', 'pid': '27889', 'message': 'Session STARTED - Client[ID:8242, Physical: 111.119.187.47, Virtual: 10.1.0.66] <--> Service[Name:Attendance1, ID:704, Physical: 192.168.3.18, Virtual: 10.1.0.67]'}",
"parsed: {'priority': '15', 'timestamp': '2021-04-13 13:42:07', 'hostname': 'invi-dev-gw3', 'rootname': 'root', 'pid': '27890', 'message': 'Session STOPPED - Client[ID:8242, Physical: 111.119.187.47, Virtual: 10.1.0.66] <--> Service[Name:Attendance1, ID:704, Physical: 192.168.3.18, Virtual: 10.1.0.67]'}"
]
data_out = collections.defaultdict(list)
for row in data_in:
command, command_text = [value.strip() for value in row.split(":", 1)]
data_out[command].append(ast.literal_eval(command_text))
print(json.dumps(data_out, indent=2))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.