我是编程新手,我创建了一个子程序来存储您的姓名,而不是列表中的项目。
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)
但是,当我运行该程序时,错误始终出现。该错误表明在第8行(该行所在的代码行)中有一个错误
username = json.load(f_obj)
这是确切的错误
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)
如果有人可以提供帮助,我们将不胜感激, 谢谢,
答案 0 :(得分:1)
您正在逐一序列化对象。 str
和list
。在list
或dict
之类的集合中执行一次。
这一作品;
>>> print(json.loads('"a"'))
a
但是str
和list
这一个错误;
>>> 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)
使用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)
现在json.load
将返回带有键dict
和username
的{{1}}。