Steve S
Steve S

Reputation: 35

Python json load error: JSONDecodeError: Expecting value

import json

filepath = 'C:/Users/ss/Documents/My Files/Python/'
filename = 'favorite_number.json'
file = filepath + filename


def get_fav_num(username):
    """ This function retrieves the username's favorite number if it's stored in the application """
       
    with open(file) as infile:
        fav_nums = json.load(infile)
        for key in fav_nums.keys():
            if key == username:
                fav_num = fav_nums[username]
                return fav_num
            else:
                return None

username = input("Please enter a username. Your username must be at least 8 characters and consist of numbers and letters: ")

if get_fav_num(username):
    fav_num = get_fav_num(username)
    print(f"Hello {username}! Your favorite number is {fav_num}.")
else:
    fav_num = int(input("Now tell me your favorite number: "))
    favorite_numbers = {}
    favorite_numbers[username] = fav_num
    with open(file, 'w') as outfile:
        append_fav_num = json.load(outfile)
        append_fav_num.update(favorite_numbers)

Here is the Traceback (most recent call last):

  File "C:\Users\ss\Documents\My Files\Python\Storing Data.py", line 78, in <module>
    if get_fav_num(username):

  File "C:\Users\ss\Documents\My Files\Python\Storing Data.py", line 68, in get_fav_num
    fav_nums = json.load(infile)

  File "C:\Users\ss\Anaconda3\lib\json\__init__.py", line 296, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)

  File "C:\Users\ss\Anaconda3\lib\json\__init__.py", line 348, in loads
    return _default_decoder.decode(s)

  File "C:\Users\ss\Anaconda3\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())

  File "C:\Users\ss\Anaconda3\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None

JSONDecodeError: Expecting value

I tried the code in get_fav_nums() on its own first and it executes perfectly. Does anyone know why I'm getting this JSONDecodeError when I put it in a function?

Upvotes: 2

Views: 206

Answers (1)

Spring Apricot
Spring Apricot

Reputation: 58

I have noticed you have a redundant ) at the very end of this script - after removing this, I managed to run your code successfully on my machine.

Upvotes: 2

Related Questions