How can I call a JSON value using Python?

Question:

I have a JSON file with some data:

{
    "item": {
        "userid":"",
        "kissed": {
            "kisseduser0":"",
            "kisseduser0times":"",
            "kisseduser1":"",
            "kisseduser1times":"",
            "kisseduser2":"",
            "kisseduser2times":""
        }
    },
    "item1": {
        "userid":"",
        "kissed": {
            "kisseduser0":"",
            "kisseduser0times":"",
            "kisseduser1":"",
            "kisseduser1times":"",
            "kisseduser2":"",
            "kisseduser2times":""
        }
    }
}
    

I’m trying to call "userid" value (In the future I’ll use kisseduser) using python, like that:

with open('dictionary.json') as f:
        d = json.load(f)
        print(d[userid])

But I can’t, here’s the output:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'userid'

I read that’s a JSON problem, "item" and "item1" are acting as keys, and "userid" & "kissed" are acting as values. How can I call a value? Or, how can I improve my JSON file? I tried in various ways, but I still can’t.

It’s worth say that I used d.keys() and d.values(), and realized that my hypothesis is true.

Also, my objective with my JSON file are that the program doesn’t take so long to search for the corresponding value, that’s why the structure that I am currently following; but if it can be improved I prefer to change it.

Asked By: Masoshi

||

Answers:

First, d[userid] will raise an exception because userid is undefined, use d["userid"] instead.

Also, have you tried to do something like:

print(d["item"]["userid"])
# or
print(d["item1"]["userid"])

Because userid is under each item.

Answered By: xihtyM
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.