Home > Net >  Accessing keys when loading from JSON
Accessing keys when loading from JSON

Time:12-01

I am new to Python and I can not seem to find a solution that I understand.
• When I load in the JSON file I can print out the list as a whole; but if I try to access the key I get KeyError.
• Am I right in saying that Python converts the JSON file into a Python dictionary?
• Also, how would I go about accessing keys and then checking against them?

Main Code:

Main code

JSON File:

JSON file

Console Error:

Console error message

CodePudding user response:

Welcome to Stackoverflow Community.

JSON you have:

{
   "credentials": [
       {
         "username": "Admin",
         "password": "Password"
       }
   ]
}

When Converted to the dictionary:

{'credentials': [{'username': 'Admin', 'password': 'Password'}]}

Understanding the output of credentials:

print(data["credentials"])

# Output: 
[{'username': 'Admin', 'password': 'Password'}] 
# Do observe that the output is in a list format.

# For better understanding let's assume there is more than 1 credential:
[
 {'username': 'Admin', 'password': 'Password'},   # 0 of list
 {'username': 'Admin1', 'password': 'Password1'}  # 1 of list 
]

Understanding the mistake:

# Instead of
data["username"]

# do
data["credentials"][0]["username"]

The Right way:

for i in len(data["credentials"]):
    print("The username is ", data["credentials"][i]["username"])

Also, I encourage you to go through Python Tutorials before working on something.
Python is widely considered among the easiest programming languages for beginners to learn.

  • Related