json not working(Python)

So I’m experimenting with the json functions and storing user entered data into another file and then loading it again, and I came into an error. I’ve looked at every single character 5 times and I can’t figure out what’s going wrong.

import json

# Load the username, if it has been stored previously.
# Otherwise, prompt for the username and store it.
filename = 'username.json'
	with open(filename) as f_obj:
		username = json.load(f_obj)
except FileNotFoundError:
	username = input("What is your name? ")
	with open(filename, 'w') as f_obj:
		json.dump(username, f_obj)
		print("We'll remember when you come back, " + username + '!')
	print('Welcome back, ' + username + '!')

And this is the error I’m getting.

Traceback (most recent call last):
  File "helloworld.py", line 8, in <module>
    username = json.load(f_obj)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.752.0_x64 __qbz5n2kfra8p0\lib\json\__ init__.py", line 293, in load
    return loads(fp.read(),
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.752.0_x64 __qbz5n2kfra8p0\lib\json\__ init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.752.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.752.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 1)

(program exited with code: 1)

Press any key to continue . . .

Please help!

Your program worked fine for me (python 3.7.4). It looks like the problem is with the json file itself, not necessarily your code. Depending on what “name” you entered, the resulting json might not be parsable (without escaping).

1 Like