Python3将API返回的bytes解码为str

前言

在调用API的时候,有些API会返回bytes类型的串,格式如下:

b'{"status":"0","msg":"ok","result":{"type":"google","from":"zh-cn","to":"en","text":"\xe4\xb8\xad\xe5\x9b\xbd",
"result":"China<br \\/><br \\/><strong>\xe5\x90\x8d\xe8\xaf\x8d<\\/strong><br \\/><span class=\\"green\\">China<\\/span> 
\xe4\xb8\xad\xe5\x9b\xbd, \xe5\x8d\x8e, \xe4\xb8\xad\xe5\x8d\x8e<br \\/>"}}'

如果将这种类型的字串直接存入到数据库的话,从数据库中读取出的字串进行操作会出现问题,比如上面的字串直接进行解析的话会直接报错,原因是str存着的实际上是一串没有解码的bytes。所以存入数据库时,要对bytes进行解码的操作。各位看官,详细操作请往下看。


bytes解码

bytes.decode(encoding='utf-8')

注:bytes为要解码的bytes串


bytes编码

S.encode(encoding='utf-8', errors='strict') -> bytes

注:S为str


源码

def decode(self, *args, **kwargs): # real signature unknown
    """
    Decode the bytes using the codec registered for encoding.
    
      encoding
        The encoding with which to decode the bytes.
      errors
        The error handling scheme to use for the handling of decoding errors.
        The default is 'strict' meaning that decoding errors raise a
        UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
        as well as any other name registered with codecs.register_error that
        can handle UnicodeDecodeErrors.
    """
    pass

def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
    """
    S.encode(encoding='utf-8', errors='strict') -> bytes
    
    Encode S using the codec registered for encoding. Default encoding
    is 'utf-8'. errors may be given to set a different error
    handling scheme. Default is 'strict' meaning that encoding errors raise
    a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
    'xmlcharrefreplace' as well as any other name registered with
    codecs.register_error that can handle UnicodeEncodeErrors.
    """
    return b""

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

桥路丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值