1. 程式人生 > >python中關於編碼,json格式的中文輸出顯示

python中關於編碼,json格式的中文輸出顯示

pri 整體 pytho src repr 接口 ensure 輸出 unicode

但我們用requests請求一個返回json的接口時候,

語法是

result=requests.post(url,data).content

print type(result),result

得到的結果是

<type ‘str‘> {"no":12,"err_code":220012,"error":null,"data":{"autoMsg":"","fid":6428441,"fname":"\u884c\u5c38\u8d70\u8089\u7b2c\u516d\u5b63","tid":0,"is_login":1,"content":"","access_state":null,"vcode":{"need_vcode":0,"str_reason":"","captcha_vcode_str":"","captcha_code_type":0,"userstatevcode":0},"is_post_visible":0,"mute_text":null}}

這種形式,可以看到結果是字符串類型,但結果中包含了一串讓人看不懂的東西 \uxxxx的,這是中文對應的unicode編碼形式。

下面我們查看result的原始內容

print repr(result)

得到的結果是

{"no":12,"err_code":220012,"error":null,"data":{"autoMsg":"","fid":6428441,"fname":"\\u884c\\u5c38\\u8d70\\u8089\\u7b2c\\u516d\\u5b63","tid":0,"is_login":1,"content":"","access_state":null,"vcode":{"need_vcode":0,"str_reason":"","captcha_vcode_str":"","captcha_code_type":0,"userstatevcode":0},"is_post_visible":0,"mute_text":null}}‘

那麽怎麽樣,顯示出中文呢,

print res_content.decode(‘raw_unicode_escape‘)

得到的結果是

{"no":12,"err_code":220012,"error":null,"data":{"autoMsg":"","fid":6428441,"fname":"行屍走肉第六季","tid":0,"is_login":1,"content":"","access_state":null,"vcode":{"need_vcode":0,"str_reason":"","captcha_vcode_str":"","captcha_code_type":0,"userstatevcode":0},"is_post_visible":0,"mute_text":null}}

這樣就能看到中文了。

另外一種方法是

print json.dumps(json.loads(result),ensure_ascii=False)

得到的結果是

{"err_code": 220012, "data": {"vcode": {"captcha_code_type": 0, "captcha_vcode_str": "", "str_reason": "", "need_vcode": 0, "userstatevcode": 0}, "is_post_visible": 0, "access_state": null, "fid": 6428441, "autoMsg": "", "content": "", "fname": "行屍走肉第六季", "tid": 0, "mute_text": null, "is_login": 1}, "error": null, "no": 12}

這樣也能顯示出中文。

上面的這句話是json.loads把json字符串轉換成字典,然後再要json.dumps轉字符串。

我們再來看看python的直接print 一個包含中文的字典或者列表,看看結果

技術分享

或者中國是一個unicode類型的

技術分享

上面兩種情況直接print 一個列表,都會顯示不出中文,除非是對列表進行遍歷,一個個的print出來,這樣才可以看到顯示中文。

或者你想原封不動的顯示出中文,那就借助print json.dumps(list,ensure_ascii=False)的用法,這樣就能整體輸出並且顯示出中文了。

python中關於編碼,json格式的中文輸出顯示