[英]json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 2 column 1 (char 2)
so I'm trying to build a library manager of sorts, as a way to practice my programming.所以我正在尝试构建一个库管理器,作为练习我的编程的一种方式。 It uses a JSON file to store book data.
它使用 JSON 文件来存储图书数据。 The problem occurs when I try to print the full list of books stored in the JSON file, in a nice format.
当我尝试以良好的格式打印存储在 JSON 文件中的完整书籍列表时,就会出现问题。 Here is the code:
这是代码:
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()
It gives me this error:它给了我这个错误:
"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
Here is the JSON file: (storage.json)这是 JSON 文件:(storage.json)
{ "name": "Lord of The Rings", "author": "J.R.R Tolkien" } { "name": "Harry Potter", "author": "JK Rowling" } { "name": "The Adventures of Huckleberry Finn", "author": "Mark Twain" }
{“名称”:“指环王”,“作者”:“J.R.R 托尔金”} {“名称”:“哈利波特”,“作者”:“JK罗琳”} {“名称”:“ 《哈克贝利·费恩历险记》、《作者》:《马克吐温》}
What am I doing wrong?我究竟做错了什么?
Your JSON file is not correctly formatted.您的 JSON 文件格式不正确。 You have:
你有:
{"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" }
You are missing commas between your lists.您的列表之间缺少逗号。 Try this instead:
试试这个:
{"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"}
Since you're describing multiple objects, you must include spaces between them to tell your JSON parser that they are, in fact, separate objects.由于您正在描述多个对象,因此您必须在它们之间包含空格以告诉您的 JSON 解析器它们实际上是单独的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.