python - 为什么 json python 程序总是出现错误

标签 python

我是编程新手,我创建了一个子程序来存储您的姓名,而不是列表中的项目。

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)

如果有人可以提供帮助,我们将不胜感激, 谢谢,

最佳答案

您正在将对象一一序列化。一个 str 和一个 list。在 listdict 等集合中执行一次。

这个有效;

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

但这一个 strlist 是一个错误;

>>> 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 将返回一个带有 usernameitems 键的 dict

关于python - 为什么 json python 程序总是出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53241589/

相关文章:

python - 如何根据另一个列表对一个列表进行排序?

python - 基本 Docopt 示例不起作用

python - 包含同名类的 Python 模块在导入时如何工作?

即使有对象,Python .get() 也不会计算为 True?

python - PIL 在 OpenCV 图像中产生灰色像素

python - 在 Django 中重组多对多关系

python - 使用 reportlab 将 .SVG 文件嵌入到 PDF 中

python - 如何从 pandas 中的一系列数据帧中删除空数据帧?

python - 如何修复 ModuleNotFound 错误?

python - 链的节点中的每个值都是由前一个值加上前一个值的数字之和计算得出的