如何为JSON字符串对象提供要读取的属性?

时间:2018-06-17 01:44:41

标签: python json

我正在尝试使用JSON从列表中选择对象,然后在选择后删除这些对象。我一直遇到错误告诉我

AttributeError: 'str' object has no attribute 'read'

error message, json file, original code

path_album_list = 'C:\\Users\\steve\\AppData\\Local\\Programs\\Python\\Python36\\albums.json'
albums = json.load(path_album_list)
album = random.choice(albums)
print ('Today\'s soundtrack is "%s."' % album)
albums.remove(album)
json.dump(albums, path_album_list)

我也尝试使用json.loads,但后来我遇到了更多错误:

Traceback (most recent call last):
  File "C:\Users\steve\AppData\Local\Programs\Python\Python36\randomizer.py", line 20, in <module>
    albums = json.loads(path_album_list)
  File "C:\Users\steve\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\Users\steve\AppData\Local\Programs\Python\Python36\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\steve\AppData\Local\Programs\Python\Python36\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)*

1 个答案:

答案 0 :(得分:1)

json.load获取文件对象,而不是字符串。所以你需要这样做:

path_album_list = 'C:\\Users\\steve\\AppData\\Local\\Programs\\Python\\Python36\\albums.json'
jsonfile = open(path_album_list, "r")
albums = json.load(jsonfile)
jsonfile.close()
# ...
jsonfile = open(path_album_list, "w")
json.dump(albums, jsonfile)
jsonfile.close()

或者,您可以使用with语句,但上述内容可能更容易理解。

path_album_list = 'C:\\Users\\steve\\AppData\\Local\\Programs\\Python\\Python36\\albums.json'
with open(path_album_list, "r") as jsonfile:
    albums = json.load(jsonfile)
# ...
with open(path_album_list, "w") as jsonfile:
    json.dump(albums, jsonfile)

您需要open文件的原因是json与文件交互,而不是文件路径的字符串。