将日志文件转换为json?

2024-10-01 13:42:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的日志文件格式如下。我需要使用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)


Tags: 文件infojsonhttptypehostnameddexec
2条回答

导入pythons json library

import json

以字符串形式读入文件,并获取“Response:”子字符串之后的所有内容:

^{pr2}$

response_string获取python对象:

response_obj = json.loads(response_string)

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

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

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

^{pr2}$

相关问题 更多 >