Aanchal Agarwal
Aanchal Agarwal

Reputation: 57

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

Upvotes: 0

Views: 4980

Answers (2)

zkdev
zkdev

Reputation: 315

Python can handle valid json's as dictionaries. Therefore you have to parse to json string to a python dictionary.

import json
dic = json.loads(json_str)

You can now access a value by using the specific key as an index 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).

Upvotes: 1

Neda Peyrone
Neda Peyrone

Reputation: 340

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

Upvotes: 1

Related Questions