Python将 Unicode 转换为 utf-8 格式

问题描述

在测试接口时,发现响应结果返回的是Unicode类型字符串,不方便问题查找与定位,因此想能否转换为 utf-8 格式字符串

import requests
import re
ConfigResponse = requests.get("https://newb2f.wonmore.com/api/v4/shop/config").text
print(ConfigResponse)
>>>{
    
    "status":"success","data":{
    
    "shop_name":"\u592e\u8054\u670d\u9970","shop_title":"\u592e\u8054\u670d\u9970","shop_desc":"","shop_keywords":"\u592e\u8054\u670d\u9970","shop_logo":"https:\/\/wo-fushi.oss-cn-zhangjiakou.aliyuncs.com\/images\/common\/shop_logo.png","shop_reg_closed":"0","lang":"zh-CN","stats_code":"","search_keywords":"\u886c\u886b,\u5939\u514b","wap_logo":"https:\/\/wo-fushi.oss-cn-zhangjiakou.aliyuncs.com\/images\/wap_logo.png","register_article_id":"","buyer_cash":"100","buyer_recharge":"21","bonus_ad":{
    
    "ad_link":"","popup_ads":"","open":0},"mp_checked":true},"time":1609984754}

解决方法

只需要一句话即可转换成功,需要注意的是,转换过程可能会报错,因此可能需要正则将部分字符串进行替换

str.encode('utf-8').decode("unicode_escape")

这是替换之后再转码的结果,中文显示正常

NewResponse = re.sub(r"/","",ConfigResponse)
print(NewResponse)
>>>{
    
    "status":"success","data":{
    
    "shop_name":"\u592e\u8054\u670d\u9970","shop_title":"\u592e\u8054\u670d\u9970","shop_desc":"","shop_keywords":"\u592e\u8054\u670d\u9970","shop_logo":"https:\\wo-fushi.oss-cn-zhangjiakou.aliyuncs.com\images\common\shop_logo.png","shop_reg_closed":"0","lang":"zh-CN","stats_code":"","search_keywords":"\u886c\u886b,\u5939\u514b","wap_logo":"https:\\wo-fushi.oss-cn-zhangjiakou.aliyuncs.com\images\wap_logo.png","register_article_id":"","buyer_cash":"100","buyer_recharge":"21","bonus_ad":{
    
    "ad_link":"","popup_ads":"","open":0},"mp_checked":true},"time":1609984754}

print(NewResponse.encode('utf-8').decode("unicode_escape"))
>>>{
    
    "status":"success","data":{
    
    "shop_name":"央联服饰","shop_title":"央联服饰","shop_desc":"","shop_keywords":"央联服饰","shop_logo":"https:\wo-fushi.oss-cn-zhangjiakou.aliyuncs.com\images\common\shop_logo.png","shop_reg_closed":"0","lang":"zh-CN","stats_code":"","search_keywords":"衬衫,夹克","wap_logo":"https:\wo-fushi.oss-cn-zhangjiakou.aliyuncs.com\images\wap_logo.png","register_article_id":"","buyer_cash":"100","buyer_recharge":"21","bonus_ad":{
    
    "ad_link":"","popup_ads":"","open":0},"mp_checked":true},"time":1609984754}

猜你喜欢

转载自blog.csdn.net/zhuan_long/article/details/112303276