2016-12-06 69 views
1

我在Python 2切换到3的UnicodeDecodeError:“GBK”编码解码器时,阅读JSON包含中国

在我jupyter笔记本代码

file = "./data/test.json" 
with open(file) as data_file:  
    data = json.load(data_file) 

过去是无法解码字节精细与Python 2,但现在后只需切换到Python 3,它给我的错误

UnicodeDecodeError: 'gbk' codec can't decode byte 0xad in position 123: illegal multibyte sequence 

test.json文件是这样的:

[{ 
    "name": "Daybreakers", 
    "detail_url": "http://www.movieinsider.com/m4120/daybreakers/", 
    "movie_tt_id": "中文" 
    }] 

如果我删除中文,将不会有错误。

那我该怎么办?

在这里有很多类似的问题,但我没有找到一个好的解决方案,我的情况。如果你找到适用的,请告诉我,我会关闭这个。

非常感谢!

回答

2

您需要在打开文件时指定正确的编码。如果JSON用UTF-8编码,你可以这样做:

import json 

fname = "test.json" 
with open(fname, encoding='utf-8') as data_file:  
    data = json.load(data_file) 

print(data) 

输出

[{'name': 'Daybreakers', 'detail_url': 'http://www.movieinsider.com/m4120/daybreakers/', 'movie_tt_id': '中文'}] 
相关问题