Search code examples
pythonjsonparsingjsonpath

JSON parsing in python using JSONPath


In the JSON below, I want to access the email-id and 'gamesplayed' field for each user.

 "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
      }
}

Following is the code that I using to try and access the users email-id:

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

This is the error I'm getting:

  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

And when I run the following line to and access the 'gamesplayed' field for each user, the IDE Crashes.

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

Solution

  • If you like to use JSONPath. Please try this.

    Python code:

    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)
    

    Output:

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