I have the below log file in the following format. I need to convert the log file into json file using python. How can it be made?
[2015-07-13 00:03:05,976] hostna
The solution using re.search()
and json
module:
import re, json
with open('logfile', 'r') as logfile,\
open('output.json', 'w') as jsonfile:
json_data = re.search(r'(Response:\s*)(.*)(?=\(HttpClientUtil\))', logfile.read(), re.DOTALL)
if json_data:
json.dump(json.loads(json_data.group(2)), jsonfile)
output.json
contents:
{"accountBalance": {"pointsName": "dd", "pointsBalance": 95053}, "pricingTier": "ggg", "userInformation": {"emailAddresses": [{"type": "OTHER", "email": "dd@YAHOO.COM"}], "title": "Mr", "middleName": "C", "lastName": "gg", "phoneNumbers": [{"type": "OTHER", "number": "5555"}], "additionalInfo": {"memberID": "dd", "memberLevel": "0", "updatedMemberID": "dd"}, "address": {"line1": "10249 dd", "countryCode": "rr", "city": "dd Park", "postalCode": "777", "stateCode": "vv"}, "firstName": "gg"}, "accountStatus": {"statusCode": "ACTIVE", "accessType": "STANDARD", "statusMessage": "Unknown"}}
Import pythons json library:
import json
Read in the file as a string and get everything after the 'Response:' substring:
with open("logfile", "r") as log_file:
log_string = log_file.read()
response_string = log_string.split("Response:")[1].strip()
Get a python object from response_string
:
response_obj = json.loads(response_string)
If you need to, write that object out to a file after doing whatever you need with it:
with open("outfile", "w") as out_file:
out_file.write(json.dumps(response_obj))