I'm very new to python and I'm trying to implement a dictionary of user names and passwords to a JSON File. I also wanted to make an error checker if there was a user name with that already exists, it'll print out an error message. That is what my for loop is for in the else statement. I tried to do "if userName in data:" method while I had my for loop commented but it would skip right over this condition and just go straight to adding it. When I add the first user name to an empty JSON file, it adds properly into the dictionary and into the JSON file. However, after this, I run into problems. When I try to add the second user and password, it gives me a KeyError 0 with my for loop.
def AddUser(userName, password):
#if file is empty, no users inside
if os.stat("users.json").st_size == 0:
user = {'user':userName,'password': password
}
with open ('users.json','w') as f:
json.dump(user,f)
data = json.load(open('users.json'))
print len(data)
print "Success"
sys.exit()
else:
#data = json.load(open('users.json')
for i in range(len(data)):
nameChecker = data[i]['user']
if(nameChecker == userName):
sys.exit("Error: username exists")
#if userName in data:
# sys.exit("Error: username exists")
data = json.load(open('users.json'))
if type (data) is dict:
data = [data]
data.append(
{
'user' : userName,
'password': password
})
with open ('users.json', 'w') as outfile:
json.dump(data,outfile)
print len(data)
print "Success"
I found out that this happens because it is recognizing the len(data) as a length of 2 but there is no 2nd user, it is still 1 user name and password. If I comment out my for loop and disregard my error check to try to add a second user, it will add the second user and add it to the JSON file and but this time it will display a length of 2 again. My json file looks like this after the first user name entered,
{"password": "password", "user": "jimmy"}
And this is what it looks like after the second one is added when commenting out the for loop
[{"password": "password", "user": "bimmy"}, {"password": "password", "user": "bimmy"}]
If I add a third user it will add the third user properly and display a length of 3 (After 2 users are added it matches the length to the number of users there currently are). I then uncomment my for loop and try to run the code with a user name that already exists, and the for loop will take care of it and display "Error: username exists". Then if I want to add a new user name with the for loop uncommented, it will add it properly without an issue. How can I take care of the error checker when I try to add my second user? and Why does inputting the first user display a length of 2 for the data when there is only one username and one password? I can't seem to get around that issue when I try to add the second user name and password. Also is there a proper way to add more user names after the JSON file was created? I tried to do data.update but I kept getting error messages, and data.append seemed to work.