LoginSignup
0
0

Python3でBase64エンコードした際の型の扱い

Posted at

Python3でBase64エンコードしたときに微妙にはまった話

環境

  • Ubuntu 18.04 on Hyper-V
  • Python 3.6.9

よくありがちなこんな感じのコード

json.dumps({"hoge": base64.b64encode("poyo".encode())})

<dict>{<str>: <str>} だからきっと通るだろうと思うと実行時にエラーになる。

TypeError: Object of type 'bytes' is not JSON serializable

bytes型になってる?どこが?ということで調べてみるとどうも base64.b64encode() はbytes型で返ってくるらしい。
つまり<dict>{<str>: <bytes>}なのでダメ、と。
それならbytesをstrに変えてあげればいいのだけれど、はてどうしたものかと。
ということでいろいろ試してみる。

#! /usr/bin/python3

import base64

def main():
    basetext = "poi poi pui pui"
    go_print(basetext)
    base64_object = base64.b64encode(basetext.encode())
    go_print(base64_object)
    base64object_decode = base64.b64encode(basetext.encode()).decode('ascii')
    go_print(base64object_decode)
    base64_object_str_cast = str(base64.b64encode(basetext.encode()))
    go_print(base64_object_str_cast)

def go_print(printdata):
    print("GP: ----- ----- -----")
    print(type(printdata))
    print(printdata)

if __name__ == "__main__":
    main()

実行した結果

GP: ----- ----- -----
<class 'str'>
poi poi pui pui
GP: ----- ----- -----
<class 'bytes'>
b'cG9pIHBvaSBwdWkgcHVp'
GP: ----- ----- -----
<class 'str'>
cG9pIHBvaSBwdWkgcHVp
GP: ----- ----- -----
<class 'str'>
b'cG9pIHBvaSBwdWkgcHVp'

ということで、「Base64エンコードした際に中身をstrで欲しいとき」には「.decode('ascii')」でデコードすると出てきますよというお話でしたとさ。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0