本文實例講述了Python實現(xiàn)的json文件讀取及中文亂碼顯示問題解決方法。分享給大家供大家參考,具體如下:
city.json文件的內(nèi)容如下:
1
2
3
4
5
6
7
8
9
10
11
12
|
{ "cities" : [ { "city" : "北京" , "cityid" : "101010100" }, { "city" : "上海" , "cityid" : "101020100" } ] } |
可見,其中包含了中文。
Python使用json.loads
之后打印中文會出現(xiàn)亂碼的問題,解決方法如下:
1
2
3
4
5
6
7
8
9
10
11
|
with open ( 'city.json' , 'r' ) as json_file: """ 讀取該json文件時,先按照gbk的方式對其解碼再編碼為utf-8的格式 """ data = json_file.read().decode(encoding = 'gbk' ).encode(encoding = 'utf-8' ) print type (data) # type(data) = 'str' result = json.loads(data) new_result = json.dumps(result,ensure_ascii = False ) # 參考網(wǎng)上的方法,***ensure_ascii***設(shè)為False print new_result # 輸出結(jié)果: # "cities": [{"cityid": "101010100", "city": "北京"}, {"cityid": "101020100", "city": "上海"}] |
希望本文所述對大家Python程序設(shè)計有所幫助。
原文鏈接:https://blog.csdn.net/wyc12306/article/details/79193583