2016-05-14 182 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文件做的是一樣的,一切正常,但寫入磁盤的文件已損壞,無法正常打開 –