Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I call a JSON value using Python?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading