如何在python中解析key是变量的json?

时间:2014-09-22 09:14:29

标签: python json logging logfiles

我正在解析一个json格式的日志文件,  并包含key:value pair形式的数据。

我被困在钥匙本身可变的地方。请查看随附的代码

在此代码中,我可以访问用户名,event_type,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 键和

这个键里面的数据??

3 个答案:

答案 0 :(得分:1)

您不需要提前知道密钥,您可以简单地遍历字典:

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

答案 1 :(得分:0)

假设您有一个类型为d = {"a":"b"}的词典,那么d.popitem()将为您提供("a","b")元组(key,value)。因此,使用它可以在不知道密钥的情况下访问键值对。

在你的情况下如果j是主词典,那么j["event"]["submission"].popitem()会给你元组

("i4x-IITB-CS101-problem-33e4aac93dc84f368c93b1d08fa984fc_2_1": {
                "input_type": "choicegroup",
                "question": "",
                "response_type": "multiplechoiceresponse",
                "answer": "MenuInflater.inflate()",
                "variant": "",
                "correct": true
            })

希望这就是你所要求的。

答案 2 :(得分:0)

使用python json模块,你将得到上述JSON数据中已解析值的字典

 import json
 parsed = json.loads(this_sample_data_in_question)
 # parsed is a dictionary, so are "correct_map" and "submission" dictionary keys within "event" key 

因此,您可以将数据的值作为普通字典迭代,如下所示:

 for k, v in parsed.items():
     print k, v

现在您可以快速找到“i4x-IITB-CS101-problem-33e4aac93dc84f368c93b1d08fa984fc_2_1”键的(可能的不同值):

import json

parsed = json.loads(the_data_in_question_as_string)
event = parsed['event']

for key, val in event.items():
    if key in ('correct_map', 'submission'):
        section = event[key]
        for possible_variable_key, its_value in section.items():
            print possible_variable_key, its_value

当然可能有更好的方法来迭代字典,但是你可以根据你的编码品味或性能来选择,如果你有比这里发布的数据更大的数据类型。

相关问题