Search code examples
pythonjsonapikeykeyerror

How to properly insert a variable into a json key in python


I don't know how to properly enter a variable into a json key. I end up getting errors on the key directly afterward. The variable I want to enter is right after ["members"] where it says str(uuids[count]).

import requests
import json

uuids = []
count = 0
catacombs = []

data = requests.get("https://api.hypixel.net/guild?key=42d64fe9-677c-433b-9460-f0177e0b9ded&id=5f1654598ea8c918612a6a43").json()
for guild in data["guild"]["members"]:
    uuids.append(guild["uuid"])

for guild in data["guild"]["members"]:
    data = requests.get("https://api.hypixel.net/skyblock/profile?key=42d64fe9-677c-433b-9460-f0177e0b9ded&profile=" + str(uuids[count])).json()
    catacombs.append(data["profile"]["members"][str(uuids[count])]["dungeons"]["dungeon_types"]["catacombs"]["experience"])
    count += 1
    print(catacombs)

Any help at all is appreciated. Thanks in advance.


Solution

  • Well, that's seems that the key dungeons didn't exist in some of the json.(And the experience, too).You could try dict.get and then to check whether it exists,

    Also, you could use zip to iterate both the uuids and data["guild"]["members"] without use a index to count them.Code below:

    import requests
    
    uuids = []
    catacombs = []
    
    data = requests.get("https://api.hypixel.net/guild?key=42d64fe9-677c-433b-9460-f0177e0b9ded&id=5f1654598ea8c918612a6a43").json()
    for guild in data["guild"]["members"]:
        uuids.append(guild["uuid"])
    
    for guild, uuid in zip(data["guild"]["members"], uuids):
        data = requests.get("https://api.hypixel.net/skyblock/profile?key=42d64fe9-677c-433b-9460-f0177e0b9ded&profile=" + uuid).json()
        if data["profile"] is None:
            print(uuid, ": the profile is None")
            continue
        dungeons = data["profile"]["members"][uuid].get("dungeons")
        if dungeons is not None:
            experience = dungeons["dungeon_types"]["catacombs"].get("experience")
            if experience is not None:
                print(uuid, ":", experience)
                catacombs.append(experience)
            else:
                print(uuid, ": has dungeons but don't have experience ")
        else:
            print(uuid, ": no dungeons.")
    
    print(catacombs)
    

    And this gave me:

    0baac74f903143e49d24015d8bc3a733 : no dungeons.
    031c3178bfd04099b34301185d1182f3 : no dungeons.
    c1558354fe2a48dabfa47cbce58cbe14 : no dungeons.
    b4a5d02f35064dda9d84b58b238d0b62 : 526339.6999999998
    69eda71c66ab4020ac394ba71dc84277 : no dungeons.
    6cf3bb8096d048aca54ae52b987b0359 : 90720.06666666668
    be3230d820b74a44a34854936499bb23 : 152437.7166666667
    24002c0cce6343f2b0a8c090719da59d : 20386.716666666656
    
    ....
    
    [526339.6999999998, 90720.06666666668, 152437.7166666667, 20386.716666666656 .... ]