python - Python将numpy数组序列化为字节串
问题描述
我需要将一个 numpy 数组序列化为 json。该值应该是一个字节字符串。API 期望数据为字符串,然后使用np.fromstring(post_data.get("mask_image"))
.
post_data = {
"room_image": bytes(Image.fromarray(image).tobytes()),
"mask_image": bytes(Image.fromarray(mask).tobytes()),
}
我也尝试过使用json.dumps
,但它给出了相同的解码错误
服务器错误:
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
解决方案
您应该简单地将字节括在双引号中,因为 JSON 格式需要它们。所以试试
post_data = {
"room_image": '"' + bytes(Image.fromarray(image).tobytes()) + '"',
"mask_image": '"' +bytes(Image.fromarray(mask).tobytes()) + '"'
}
希望能帮助到你 :)
推荐阅读
- cassandra - Cassandra 节点处于活动状态(已退出)?
- openstack - 是否有基于 Xen 与 KVM 以 PV 模式运行的 OpenStack 发行版?
- sql-server - (SQL) 尝试创建一个触发器,通常将数据映射到历史表并进行错误检查
- php - PHP PDO 无法让 MySQL 创建过程和更改表?
- javascript - 正则表达式从日志文件中解析一行
- java - 如何更改 Java 中的分隔符?
- php - 无法访问我的 Symfony 控制器 @Route
- python - Telegram bot 未从 webhook 获取更新
- java - 有人请解释Java代码语法中的收缩
- node.js - 在多个浏览器上运行 javascript 测试