[英]how to convert txt file into json using python?
我正在使用 python 編寫日志文件,日志文件是這樣的:
MessageName:mouse left down | TimeStamp:2019-02-13 15:43:31.664 | Window:13500784 | Position:(483, 587) | Wheel:0
MessageName:mouse left up | TimeStamp:2019-02-13 15:43:31.873 | Window:13500784 | Position:(483, 587) | Wheel:0
我想將此日志轉換為json格式。
這是我嘗試過的代碼:
import json
def convert() :
f = open("log_events.log", "r")
content = f.read()
splitcontent = content.splitlines()
for line in splitcontent :
pipesplit = line.split(' | ')
print(pipesplit)
with open("json_log.json", 'a') as fout:
json.dump(pipesplit, fout, indent=4)
我需要的輸出是這樣的:
[
{
"MessageName" : "mouse left down",
"TimeStamp" : "2019-02-13 15:43:31.664",
"Window" : "13500784",
"Position" : "(483, 587)",
"Wheel" : 0"
},
{
"MessageName" : "mouse left up",
"TimeStamp" : "2019-02-13 15:43:31.873",
"Window" : "13500784",
"Position" : "(483, 587)",
"Wheel" : "0"
},
]
但是使用上面給出的代碼,我的輸出是
[
"MessageName" : "mouse left down",
"TimeStamp" : "2019-02-13 15:43:31.664",
"Window" : "13500784",
"Position" : "(483, 587)",
"Wheel" : 0"
][
"MessageName" : "mouse left up",
"TimeStamp" : "2019-02-13 15:43:31.873",
"Window" : "13500784",
"Position" : "(483, 587)",
"Wheel" : "0"
]
如何轉換為正確的 JSON 格式?
您可以使用簡單的split
和解析,如下所示:)
$ cat file.txt
MessageName:mouse left down | TimeStamp:2019-02-13 15:43:31.664 | Window:13500784 | Position:(483, 587) | Wheel:0
MessageName:mouse left up | TimeStamp:2019-02-13 15:43:31.873 | Window:13500784 | Position:(483, 587) | Wheel:0
# cat mkdict.py
import json
with open('file.txt') as file, open('dump.json', 'w') as json_file:
items = []
for line in file:
if not line.strip():
continue
d = {}
data = line.split('|')
for val in data:
key, sep, value = val.partition(':')
d[key.strip()] = value.strip()
items.append(d)
json.dump(items, json_file)
print(items)
$ python mkdict.py
[{'Wheel': '0', 'TimeStamp': '2019-02-13 15:43:31.664', 'Window': '13500784', 'Position': '(483, 587)', 'MessageName': 'mouse left down'}, {'Wheel': '0', 'TimeStamp': '2019-02-13 15:43:31.873', 'Window': '13500784', 'Position': '(483, 587)', 'MessageName': 'mouse left up'}]
$ cat dump.json
[{"Wheel": "0", "TimeStamp": "2019-02-13 15:43:31.664", "Window": "13500784", "Position": "(483, 587)", "MessageName": "mouse left down"}, {"Wheel": "0", "TimeStamp": "2019-02-13 15:43:31.873", "Window": "13500784", "Position": "(483, 587)", "MessageName": "mouse left up"}]
您需要為每一行添加額外的處理,將字符串轉換為鍵:值對,然后將該對添加到字典中。
此外,您只需要打開 JSON 文件一次並寫入整個數據結構:
import json
def line_to_dict(split_Line):
# Assumes that the first ':' in a line
# is always the key:value separator
line_dict = {}
for part in split_Line:
key, value = part.split(":", maxsplit=1)
line_dict[key] = value
return line_dict
def convert() :
f = open("log_events.log", "r")
content = f.read()
splitcontent = content.splitlines()
# Split each line by pipe
lines = [line.split(' | ') for line in splitcontent]
# Convert each line to dict
lines = [line_to_dict(l) for l in lines]
# Output JSON
with open("json_log.json", 'w') as fout:
json.dump(lines, fout, indent=4)
以下代碼應該與列表和字典一起使用
import json
logfile = open('log_events.log')
#initialising a list to append all the log lines formatted as json
log_list = []
for line in logfile:
# splitting on '|'
pipe_split = [ele.strip() for ele in line.split("|")]
# initialising dictionary to fill the line splitted data in key-value pairs
line_dict = dict()
for ele in pipe_split:
# splitting on first occurrence of ':'
key,val = ele.split(":",1)
line_dict[key] = val
# appending the key-value data of each line to a list
log_list.append(line_dict)
with open('json_log.json','w') as f:
json.dump(log_list,f,indent=4)
以以下格式將輸出輸出到文件,
[
{
"MessageName": "mouse left down",
"TimeStamp": "2019-02-13 15:43:31.664",
"Window": "13500784",
"Position": "(483, 587)",
"Wheel": "0"
},
{
"MessageName": "mouse left up",
"TimeStamp": "2019-02-13 15:43:31.873",
"Window": "13500784",
"Position": "(483, 587)",
"Wheel": "0"
}
]
你那里大多是正確的。 你沒有做的是生成dict
s。
split
:
dump
它們dump
到您的.json
。魔法就在這一行:
d.append(dict(s.split(':',1) for s in l))
用字詞:在第一次出現時拆分每個元素:
對於l
每個元素,然后將它們放入一個 dict 並將它們附加到列表d
工作示例:
import json
f = open("log.file", "r")
content = f.read()
splitcontent = content.splitlines()
d = []
for v in splitcontent:
l = v.split(' | ')
d.append(dict(s.split(':',1) for s in l))
with open("json_log.json", 'w') as file:
file.write((json.dumps(d, indent=4, sort_keys= False)))
輸出:
[
{
"MessageName": "mouse left down",
"TimeStamp": "2019-02-13 15:43:31.664",
" Window": "13500784",
"Position": "(483, 587)",
"Wheel": "0"
},
{
"MessageName": "mouse left up",
"TimeStamp": "2019-02-13 15:43:31.873",
"Window": "13500784",
"Position": "(483, 587)",
"Wheel": "0"
}
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.