java base64 json,以JSON序列化base64编码的数据

I'm writing a script to automate data generation for a demo and I need to serialize in a JSON some data. Part of this data is an image, so I encoded it in base64, but when I try to run my script I get:

Traceback (most recent call last):

File "lazyAutomationScript.py", line 113, in

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

As far as I know, a base64-encoded-whatever (a PNG image, in this case) is just a string, so it should pose to problem to serializating. What am I missing?

解决方案

You must be careful about the datatypes.

If you read a binary image, you get bytes.

If you encode these bytes in base64, you get ... bytes again! (see documentation on b64encode)

json can't handle raw bytes, that's why you get the error.

I have just written some example, with comments, I hope it helps:

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值