2016-05-14 183 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文件做的是一样的,一切正常,但写入磁盘的文件已损坏,无法正常打开 –