天天看點

json庫報錯(TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper)

使用json庫導入json檔案時,報錯

TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper

json庫報錯(TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper)
import json

f = open("data/data_李佳琦.json","r")
data = json.loads(f)
print(data)
           

報錯原因是loads方法去将json檔案轉換為python對象

json有四個方法:dumps、loads、dump和load。dumps和loads是在記憶體中轉換(python對象和json字元串之間的轉換),而dump和load則是對應于檔案的處理。

修改為:

import json

f = open("data/data_李佳琦.json","r")
str = f.read()
data = json.loads(str)
print(data)
           

即可成功運作

繼續閱讀