2016-05-14 10 views
13

デモ用のデータ生成を自動化するためのスクリプトを作成しています。JSONでデータをシリアル化する必要があります。このデータの一部はイメージですので、私は、base64でエンコードが、私は私のスクリプトを実行しようとすると、私が取得:JSONでbase64でエンコードされたデータをシリアル化

Traceback (most recent call last): 
    File "lazyAutomationScript.py", line 113, in <module> 
    json.dump(out_dict, outfile) 
    File "/usr/lib/python3.4/json/__init__.py", line 178, in dump 
    for chunk in iterable: 
    File "/usr/lib/python3.4/json/encoder.py", line 422, in _iterencode 
    yield from _iterencode_dict(o, _current_indent_level) 
    File "/usr/lib/python3.4/json/encoder.py", line 396, in _iterencode_dict 
    yield from chunks 
    File "/usr/lib/python3.4/json/encoder.py", line 396, in _iterencode_dict 
    yield from chunks 
    File "/usr/lib/python3.4/json/encoder.py", line 429, in _iterencode 
    o = _default(o) 
    File "/usr/lib/python3.4/json/encoder.py", line 173, in default 
    raise TypeError(repr(o) + " is not JSON serializable") 
    TypeError: b'iVBORw0KGgoAAAANSUhEUgAADWcAABRACAYAAABf7ZytAAAABGdB... 
    ... 
    BF2jhLaJNmRwAAAAAElFTkSuQmCC' is not JSON serializable 

私の知る限りでは、base64でエンコードされた - 何でも(PNG画像、この場合)は単なる文字列なので、問題を直列化する必要があります。私は何が欠けていますか?

答えて

21

データ型には注意が必要です。

バイナリイメージを読み取ると、バイト数が取得されます。 これらのバイトをbase64でエンコードすると、...バイトがもう一度得られます! (b64encodeのドキュメントを参照してください)

jsonは未処理のバイトを処理できません。そのため、エラーが発生します。

私はコメントで、いくつかの例を書かれている、私はそれが役に立てば幸い:

from base64 import b64encode 
from json import dumps 

ENCODING = 'utf-8' 
IMAGE_NAME = 'spam.jpg' 
JSON_NAME = 'output.json' 

# first: reading the binary stuff 
# note the 'rb' flag 
# result: bytes 
with open(IMAGE_NAME, 'rb') as open_file: 
    byte_content = open_file.read() 

# second: base64 encode read data 
# result: bytes (again) 
base64_bytes = b64encode(byte_content) 

# third: decode these bytes to text 
# result: string (in utf-8) 
base64_string = base64_bytes.decode(ENCODING) 

# optional: doing stuff with the data 
# result here: some dict 
raw_data = {IMAGE_NAME: base64_string} 

# now: encoding the data to json 
# result: string 
json_data = dumps(raw_data, indent=2) 

# finally: writing the json string to disk 
# note the 'w' flag, no 'b' needed as we deal with text here 
with open(JSON_NAME, 'w') as another_open_file: 
    another_open_file.write(json_data) 
+0

私は、この特定のアクション 'リターン{「生」でメールを送信するためにGmailのAPIを使用していたとき、私は同様の問題がありました: base64.urlsafe_b64encode(message.as_string())} '。 @spkyあなたの答えをありがとう! – InamTaj

+1

私はExcelファイルで同じことをしていますが、すべてが正しく実行されていますが、ディスクに書き込まれたファイルが破損していて、正常に開くことができませんでした –

関連する問題