我正在解析json格式的日誌文件, 幷包含key:value對形式的數據。如何解析JSON其中鍵在python中是可變的?
我被困在鑰匙本身變化的地方。請在此代碼,我能夠訪問諸如用戶名,EVENT_TYPE,IP等關鍵看附代碼
問題對我來說是進入「提交」鍵內的值,其中
i4x-IITB-CS101-問題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-問題33e4aac93dc84f368c93b1d08fa984fc_2_1鍵和
這個關鍵內部的數據? ?
感謝回覆farzad 我已經添加了我的代碼,請檢查它,我該如何適合您的代碼? – rajsinghaniaful 2014-09-22 10:25:32
上面的示例代碼將適用於問題中提到的問題。變量「its_value」是你的問題的答案。它是一個字典,具有「提示」,「hintmode」鍵......但我不認爲你正在閱讀日誌文件行的方式是正確的。 True_和_next(infile)_沒有必要。 _for_循環將讀取文件的所有行並嘗試解析每行的JSON內容。 – farzad 2014-09-22 15:07:28