Python: Parse text file to a formatted json file

0

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"?

python
json
parsing
asked on Stack Overflow Jul 25, 2020 by tester • edited Jul 25, 2020 by Mark Tolonen

1 Answer

2

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)
answered on Stack Overflow Jul 25, 2020 by user3452643

User contributions licensed under CC BY-SA 3.0