Arun
Arun

Reputation: 55

Converting log file to json?

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] hostname 1499918592344 UZA:Anonymous:Anonymous96B50456767E74F51FD6AD2730C24133 http-nio-8080-exec-61 INFO Got successful response for the url GET http:/hostname/uza/accounts/123456789?loginTime=2017-07-13T00:03:04EDT Response: {"accountBalance":{"pointsBalance":95053,"pointsName":"dd"},"accountStatus":{"accessType":"STANDARD","statusCode":"ACTIVE","statusMessage":"Unknown"},"userInformation":{"additionalInfo":{"memberID":"dd","updatedMemberID":"dd","memberLevel":"0"},"address":{"line1":"10249 dd","city":"dd Park","stateCode":"vv","postalCode":"777","countryCode":"rr"},"emailAddresses":[{"email":"[email protected]","type":"OTHER"}],"firstName":"gg","lastName":"gg","middleName":"C","phoneNumbers":[{"number":"5555","type":"OTHER"}],"title":"Mr"},"pricingTier":"ggg"} (HttpClientUtil)

Upvotes: 1

Views: 15489

Answers (2)

Oliver Browne
Oliver Browne

Reputation: 51

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))

Upvotes: 2

RomanPerekhrest
RomanPerekhrest

Reputation: 92904

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": "[email protected]"}], "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"}}

Upvotes: -1

Related Questions