Why does an error keep showing up in a json python program

I am new to programming and I created a son program that stores your name, than the items in your list.

import json

list_ = []

filename = 'acco.json'
try:
    with open(filename) as f_obj:
        username = json.load(f_obj)
except FileNotFoundError:
    username = input("What is your name? ")
    while True:
        list_items = input("What is the item you want to add? q to quit")
        if list_items == 'q':
            break
        list_.append(list_items)
    with open(filename, 'w') as f_obj:
        json.dump(username, f_obj)
        print("These is your list of items:")
        print(list_)
        print("We'll remember you when you come back, " + username + "!")
        json.dump(list_items, f_obj)

else:
    print("Welcome back, " + username + "!")
    print("Here are the items of your list:")
    print(_list)

However, an error keeps showing up when I run the program. The error says that there is an error in line 8, the line of code where it says

username = json.load(f_obj)

This is the exact error

Traceback (most recent call last):
  File "/Users/dgranulo/Documents/rememberme.py", line 8, in <module>
    username = json.load(f_obj)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 296, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 348, in loads
    return _default_decoder.decode(s)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 340, in decode
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 8 (char 7)

If anyone can help that would be greatly appreciated, Thanks,

Upvotes: 1

Views: 661

Answers (1)

Nizam Mohamed
Nizam Mohamed

Reputation: 9220

You're serializing objects one by one. A str and a list. Do it once in a collection like a list or dict.

This one works;

>>> print(json.loads('"a"'))
a

But this one a str and a list is an error;

>>> json.loads('"a"[1]')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.6/json/decoder.py", line 342, in decode
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 4 (char 3)

Write to the file with a dict;

with open(filename, 'w') as f_obj:
    # json.dump(username, f_obj)
    print("These is your list of items:")
    print(list_)
    print("We'll remember you when you come back, " + username + "!")
    # json.dump(list_items, f_obj)
    # dump a dict
    json.dump({'username': username, 'items': list_}, f_obj)

Now json.load will return a dict with keys username and items.

Upvotes: 1

Related Questions