首页 > 解决方案 > 使用 JSONPath 在 python 中解析 JSON

问题描述

在下面的 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 的代码:

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

标签: pythonjsonparsingjsonpath

解决方案


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

推荐阅读