使用JSONPath在python中解析JSON

2024-09-30 02:30:41 发布

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

在下面的JSON中,我想访问每个用户的email id和“gamesplayed”字段。在

 "UserTable" : {
     "abcd@gmailcom" : {
        "gameHistory" : {
           "G1" : [ {
             "category" : "1",
             "questiontext" : "What is the cube of 2 ?"
           }, {
             "category" : "2",
             "questiontext" : "What is the cube of 4 ?"
           } ]
         },
        "gamesplayed" : 2
      },
     "xyz@gmailcom" : {
        "gameHistory" : {
           "G1" : [ {
             "category" : "1",
             "questiontext" : "What is the cube of 2 ?"
           }, {
             "category" : "2",
             "questiontext" : "What is the cube of 4 ?"
           } ]
         },
        "gamesplayed" : 2
      }
}

以下是我用来尝试访问用户电子邮件id的代码:

^{pr2}$

这是我得到的错误:

  File "C:\ProgramData\Anaconda3\lib\site-packages\jsonpath_rw\jsonpath.py", line 444, in find
    return [DatumInContext(datum.value[self.index], path=self, context=datum)]

KeyError: 0

当我运行下面的行并访问每个用户的“gamesplayed”字段时,IDE崩溃了。在

print (parser.ExtentedJsonPathParser().parse("$.*.gamesplayed").find(gd_info))

Tags: ofthe用户idisfindwhatjsonpath
2条回答

如果您喜欢使用JSONPath。请试试这个。在

Python代码:

with open(json_file) as json_file:
    raw_data = json.load(json_file)

jsonpath_expr = parse('$.UserTable')
players = [match.value for match in jsonpath_expr.find(raw_data)][0]
emails = players.keys()

result = [{'email': email, 'gamesplayed': players[email]['gamesplayed']} for email in emails ]
print (result)

输出:

^{pr2}$

Python可以将有效的json作为字典处理。因此,您必须将json字符串解析为python字典。

import json
dic = json.loads(json_str)

现在可以通过使用特定键作为索引value = dict[key]来访问值。

^{pr2}$

相关问题 更多 >

    热门问题