json - 在 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-encoded-whatever(在本例中为 PNG 图像)只是一个字符串,因此它应该会给序列化带来问题。我错过了什么?

最佳答案

您必须小心数据类型。

如果你读取二进制图像,你会得到字节。 如果您在 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)

https://stackoverflow.com/questions/37225035/

相关文章:

javascript - 属性名称的 JSON 语法

json - 如何在 jq 中将 JSON 对象转换为 key=value 格式?

java - JSON 对象中值的顺序是否重要?

java - 使用 jackson JsonNodeFactory 的最佳方式

python - 将 Json 嵌套到具有特定格式的 pandas DataFrame

json - 从 react 组件进行 REST 调用

python - Pandas 数据框到没有索引的json

javascript - 列表/数组是有效的 JSON 吗?

c# - 返回 JSON 对象 (ASP.NET WebAPI)

javascript - Rails 中奇怪的 JSON Javascript 问题