【发布时间】:2014-09-22 09:14:29
【问题描述】:
我正在解析一个 json 格式的日志文件, 并以 key : value 对的形式包含数据。
我被困在键本身可变的地方。请看附件代码
在这段代码中,我可以访问用户名、事件类型、ip 等键。
我的问题是访问“提交”键中的值
i4x-IITB-CS101-problem-33e4aac93dc84f368c93b1d08fa984fc_2_1是一个可变键,会因不同的用户而改变,
如何将其作为变量访问?
{
"username": "batista",
"event_type": "problem_check",
"ip": "127.0.0.1",
"event": {
"submission": {
"i4x-IITB-CS101-problem-33e4aac93dc84f368c93b1d08fa984fc_2_1": {
"input_type": "choicegroup",
"question": "",
"response_type": "multiplechoiceresponse",
"answer": "MenuInflater.inflate()",
"variant": "",
"correct": true
}
},
"success": "correct",
"grade": 1,
"correct_map": {
"i4x-IITB-CS101-problem-33e4aac93dc84f368c93b1d08fa984fc_2_1": {
"hint": "",
"hintmode": null,
"correctness": "correct",
"npoints": null,
"msg": "",
"queuestate": null
}
}
这是我解决问题的代码:
import json
import pprint
with open("log.log") as infile:
# Loop until we have parsed all the lines.
for line in infile:
# Read lines until we find a complete object
while (True):
try:
json_data = json.loads(line)
username = json_data['username']
print "username :- " + username
except ValueError:
line += next(infile)
如何访问 i4x-IITB-CS101-problem-33e4aac93dc84f368c93b1d08fa984fc_2_1 密钥和
这个键里面的数据??
【问题讨论】:
标签: python json logging logfiles