python-3.x json.decoder.JSONDecodeError:属性名称应括在双引号中:第2行第1列(字符2)

b5buobof  于 2022-12-24  发布在  Python
关注(0)|答案(1)|浏览(140)

因此,我尝试构建一个图书管理器,作为练习编程的一种方式。它使用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:\LibraryManager\venv\Scripts\python.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:\Python\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "F:\Python\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "F:\Python\lib\json\decoder.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文件:(存储. 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"
}

我哪里做错了?

bvjxkvbb

bvjxkvbb1#

您的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解析器它们实际上是独立的对象。

相关问题