json.decoder.JSONDecodeError:需要用双引号括起来的属性名:第2行第1列(字符2)



所以我正在尝试构建一个库管理器,作为练习编程的一种方式。它使用JSON文件来存储图书数据。当我试图以一种良好的格式打印JSON文件中存储的书籍的完整列表时,就会出现问题。这是代码:

import json
book = {}
def add_book():
book['name'] = input('Enter a book name: ')
book['author'] = input('Enter the author: ')
with open('storage.json', 'a') as storage:
json.dump(book, storage)

def list_books():
file = open('storage.json', 'r').readlines()
for x in file:
book.update(json.loads(x))
list_books()

它给了我这个错误:

"F:LibraryManagervenvScriptspython.exe" "F:/LibraryManager/database.py"
Traceback (most recent call last):
File "F:/LibraryManager/database.py", line 22, in <module>
list_books()
File "F:/LibraryManager/database.py", line 15, in list_books
book.update(json.loads(x))
File "F:Pythonlibjson__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "F:Pythonlibjsondecoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "F:Pythonlibjsondecoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 2 column 1 (char 2)
Process finished with exit code 1

这是JSON文件:(storage.JSON(

{
"name": "Lord of The Rings",
"author": "J.R.R Tolkien"
}
{
"name": "Harry Potter",
"author": "J.K Rowling"
}
{
"name": "The Adventures of Huckleberry Finn",
"author": "Mark Twain"
}

我做错了什么?

您的JSON文件格式不正确。您有:

{"name": "Lord of The Rings", "author": "J.R.R Tolkien" } 
{"name": "Harry Potter", "author": "J.K Rowling" } 
{"name": "The Adventures of Huckleberry Finn", "author": "Mark Twain" }

您的列表中缺少逗号。试试这个:

{"name": "Lord of The Rings", "author": "J.R.R Tolkien"}, /* << comma here is mandatory! */
{"name": "Harry Potter", "author": "J.K Rowling"},
{"name": "The Adventures of Huckleberry Finn", "author": "Mark Twain"}

由于您要描述多个对象,因此必须在它们之间包含空格,以告诉JSON解析器它们实际上是独立的对象。

相关内容

最新更新