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

3
  • What needs to change? Commented Jul 25, 2020 at 2:50
  • 1
    Please provide a sample for the .txt file Commented Jul 25, 2020 at 2:55
  • Thanks a lot for your time. I manage to get the formatted line. Commented Jul 25, 2020 at 5:32

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.