首页 > 解决方案 > 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)

标签: pythonjsonnumpypython-requests

解决方案


您应该简单地将字节括在双引号中,因为 JSON 格式需要它们。所以试试

post_data = {
        "room_image": '"' + bytes(Image.fromarray(image).tobytes()) + '"',
        "mask_image": '"' +bytes(Image.fromarray(mask).tobytes()) + '"'
    }

希望能帮助到你 :)


推荐阅读