将日志文件转换为json?

时间:2017-07-20 14:52:11

标签: python json

我有以下格式的以下日志文​​件。我需要使用python将日志文件转换为json文件。怎么做?

[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":"dd@YAHOO.COM","type":"OTHER"}],"firstName":"gg","lastName":"gg","middleName":"C","phoneNumbers":[{"number":"5555","type":"OTHER"}],"title":"Mr"},"pricingTier":"ggg"} (HttpClientUtil)

2 个答案:

答案 0 :(得分:1)

导入pythons json library

import json

将该文件作为字符串读入,并在“响应”之后获取所有内容:'子:

with open("logfile", "r") as log_file:
    log_string = log_file.read()
response_string = log_string.split("Response:")[1].strip()

response_string获取python对象:

response_obj = json.loads(response_string)

如果需要,请在完成所需操作后将该对象写入文件:

with open("outfile", "w") as out_file:
    out_file.write(json.dumps(response_obj))

答案 1 :(得分:0)

使用re.search()json模块的解决方案:

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内容:

{"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"}}