当我们用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":"u884cu5c38u8d70u8089u7b2cu516du5b63","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)的用法,这样就能整体输出并且显示出中文了。