将.json文件加载到Python中;UnicodeDecodeError

6
我尝试将一个json文件加载到python中,但一直没有成功。在过去的几个小时里我一直在寻找解决方案,但似乎无法找到正确的方法来进行加载。我已经尝试使用同样可以让其他人成功加载的json.load('filename')函数来加载,但是一直报错: "UnicodeDecodeError: 'utf8' codec can't decode byte 0xc2 in postion 124: invalid continuation byte" 以下是我的代码:
import json
json_data = open('myfile.json')
for line in json_data:
    data = json.loads(line) <--I get an error at this. 

这是我文件中的一行示例

{"topic":"security","question":"Putting the Biba-LaPadula Mandatory Access Control Methods to Practise?","excerpt":"Text books on database systems always refer to the two Mandatory Access Control models; Biba for the Integrity objective and Bell-LaPadula for the Secrecy or Confidentiality objective.\n\nText books ...\r\n        "}

如果在我谷歌搜索到的每个例子中,似乎这都起作用了,那么我的错误是什么?

在循环的每一步中,您将覆盖数据。也许您想使用+=而不是=... - Haleemur Ali
1
为什么你要逐行加载?试试data = json.load(json_data) - Burhan Khalid
@BurhanKhalid 我想解析每一行并将主题、问题和摘录分别存储 - user3890141
2个回答

11

在添加.decode("utf-8")后,我仍然遇到相同的错误。 - user3890141
这似乎允许文件加载!(Y) - user3890141
1
你会如何使用load()方法来代替loads()方法完成这个任务? - krose

0
如果Academiphile提供的方法不起作用,可以尝试这个:
with open('path/to/file.json', encoding='utf-8') as file:
    model = json.load(file)

将其添加到open()函数中,可以通过json.load()函数来实现。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接