How do you compare data keys in a dictionary from a JSON file in Python?

Viewed 91

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.

1 Answers

First time on file creation you should create a list of dict, not just dict, so instead of:

user = {'user':userName,'password': password}

do

user = [{'user':userName,'password': password}]

this above fixes main issue.

Also sys.exit() is probably not needed if you want to call function multiple times in one run. Also I uncommented data = json.load(open('users.json')).

Also would be nice to close opened for read files too, so instead of:

data = json.load(open('users.json'))

do

    with open('users.json') as f:
        data = json.load(f)

Full corrected with suggestions code down below:

Try it online too!

import sys, os, json

def AddUser(userName, password):
    #if file is empty, no users inside
    if not os.path.exists('users.json'):
        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:
        with open('users.json') as f:
            data = json.load(f)

        
        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")

# Tests
if os.path.exists('users.json'):
    os.remove('users.json')
AddUser('a', 'b')
AddUser('c', 'd')
Related