You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中含二进制文件的JSON验证失败问题求助

解决包含二进制文件的JSON验证失败问题

问题根源

你直接将读取到的二进制字节流(bytes类型)存入JSON对象的image字段,但JSON本身不支持原生二进制数据,必须转换为Base64编码的字符串才能符合JSON的字符串类型要求。之前修改Schema的尝试没解决核心问题,因为字节流本身不符合JSON数据类型规范。

解决方案步骤

  1. 将二进制文件转为Base64字符串
    使用Python的base64模块,把读取到的二进制数据编码为Base64字符串(注意要将编码后的bytes解码为str类型)。
  2. 匹配Schema配置
    保持Schema中image字段为"type": "string",如果你的验证工具支持"format": "binary"(比如jsonschema库),可以保留该格式约束;如果工具不支持,仅保留"type": "string"即可。

修改后的代码示例

import base64

def upload_image(self, image_path, title, description):
    self.collection = self.db["images"]
    with open(image_path, "rb") as image_file:
        image_binary = image_file.read()
    # 将二进制数据转为Base64字符串
    image_base64 = base64.b64encode(image_binary).decode('utf-8')

    document = {
        "title": title,
        "description": description,
        "image": image_base64
    }
    if Util.validate_json(document, self.schema):
        print("JSON data is valid")
        res = super().insert('images', document)
    else:
        print("JSON data is not valid")

对应的JSON Schema

如果验证工具支持binary格式:

{
    "type": "object",
    "properties": {
        "title": {"type": "string"},
        "description": {"type": "string"},
        "image": {
            "type": "string",
            "format": "binary"
        }
    },
    "required": ["title", "description", "image"]
}

如果验证工具不支持binary格式,简化为:

{
    "type": "object",
    "properties": {
        "title": {"type": "string"},
        "description": {"type": "string"},
        "image": {"type": "string"}
    },
    "required": ["title", "description", "image"]
}

额外注意事项

  • 确认你的Util.validate_json方法是否支持JSON Schema的format关键字,如果不支持,去掉"format": "binary"即可,仅验证字符串类型就能通过。
  • 不要直接将bytes类型数据放入JSON对象,这不符合JSON数据结构规范,必须转换为字符串或其他JSON支持的类型。

内容的提问来源于stack exchange,提问作者user2436333

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 06:04:51