Python3将API返回的bytes解码为str

时间:2022-06-18
本文章向大家介绍Python3将API返回的bytes解码为str,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

前言

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

b'{"status":"0","msg":"ok","result":{"type":"google","from":"zh-cn","to":"en","text":"xe4xb8xadxe5x9bxbd",
"result":"China<br \/><br \/><strong>xe5x90x8dxe8xafx8d<\/strong><br \/><span class=\"green\">China<\/span> 
xe4xb8xadxe5x9bxbd, xe5x8dx8e, xe4xb8xadxe5x8dx8e<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""