JSON 使用 JSON 路径在 python 中解析

JSON parsing in python using JSONPath

在下面的 JSON 中,我想访问每个用户的电子邮件 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 的代码:

for user in jp.match("$.UserTable[*].[0]", game_data):
    print("User ID's {}".format(user_id))

这是我遇到的错误:

  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))

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

import json
dic = json.loads(json_str)

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

for user in dic:
    email = user
    gamesplayed = dic[user][gamesplayed]
    print("{} played {} game(s).".format(email, gamesplayed))

>>> abcd@gmailcom played 2 game(s).
    xyz@gmailcom played 2 game(s).

如果你喜欢使用 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)

输出:

[{'email': 'abcd@gmailcom', 'gamesplayed': 2}, {'email': 'xyz@gmailcom', 'gamesplayed': 2}]