【问题标题】:json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 2 column 1 (char 2)json.decoder.JSONDecodeError:期望用双引号括起来的属性名称:第 2 行第 1 列(字符 2)
【发布时间】:2020-08-09 06:27:05
【问题描述】:

所以我正在尝试构建一个库管理器,作为练习我的编程的一种方式。它使用 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 文件:(storage.json)

{ “名称”:“指环王”, “作者”:“J.R.R 托尔金” } { “名称”:“哈利波特”, “作者”:“J.K罗琳” } { “名称”:“哈克贝利·费恩历险记”, “作者”:“马克吐温” }

我做错了什么?

【问题讨论】:

  • 我会说你做错了两件事:1)试图将非 JSON 读取为 JSON。 2) 发布此内容而不显示您的文件内容。
  • 以附加模式打开文件将连接 JSON 对象。结果将无效。解析原文,更改数据,以w模式转储数据!也不要为书籍使用单一的全局字典!
  • 您的文件很可能包含单引号 ' 而不是双引号 "
  • @KlausD。如果他们使用w,那么该文件只包含一个对象而丢失所有其他对象。
  • @MisterNox 。不,它有双引号。

标签: python python-3.x


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-14
    • 2021-04-12
    • 2021-12-31
    • 2019-01-04
    • 2018-08-02
    相关资源
    最近更新 更多