python368安装步骤图解-如何解析python中key是变量的json?

i am parsing a log file which is in json format,

and contains data in the form of key : value pair.

i was stuck at place where key itself is variable. please look at the attached code

in this code i am able to access keys like username,event_type,ip etc.

problem for me is to access the values inside the "submission" key where

i4x-IITB-CS101-problem-33e4aac93dc84f368c93b1d08fa984fc_2_1 is a variable key which will change for different users,

how can i access it as a variable ?

{

"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

}

}

this is my code how i am solving it :

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)

how can i access i4x-IITB-CS101-problem-33e4aac93dc84f368c93b1d08fa984fc_2_1 key and

data inside this key ??

解决方案

You don"t need to know the key in advance, you can simply iterate over the dictionary:

for k,v in obj["event"]["submission"].iteritems():

print(k,v)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值