I have a text file and need to extract some information and write it into a JSON file in a formatted way.
Text file:
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
Required JSON formatted way:
{'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'}
Code:
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))
Output:
[{'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'}]
Questions:
What must I do in order to make code output to be the same as the "Required JSON formatted way"?
think this works (help from Dump two dictionaries 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)
User contributions licensed under CC BY-SA 3.0