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

Python3中bytes类型JSON序列化报错及传参问题求助

问题解决方法

错误原因分析

  1. 第一个错误:'my data'.encode()生成的是bytes类型,如果my_func内部需要对参数做JSON序列化,bytes无法直接被JSON序列化,因此抛出TypeError: Object of type bytes is not JSON serializable。
  2. 第二个错误:你用json.dumps()把包含bytes的字典转成了JSON字符串,但my_func实际期望接收的是字典参数而非JSON字符串,函数内部尝试处理时因此抛出TypeError: cannot convert dictionary update sequence element #0 to a sequence。

正确实现步骤(满足Base64编码文本要求)

核心是先将原始文本编码为Base64格式的字符串,再根据my_func的参数要求传递:

情况1:my_func期望接收字典参数

import base64

# 1. 原始字符串转bytes,做Base64编码后解码为字符串
plaintext_b64 = base64.b64encode('my data'.encode('utf-8')).decode('utf-8')

# 2. 构造字典传入函数
my_response = my_func(plaintext=plaintext_b64)

情况2:my_func期望接收JSON格式的字符串参数

如果my_func需要的是JSON字符串,先构造包含Base64字符串的字典,再用json.dumps()序列化:

import base64
import json

plaintext_b64 = base64.b64encode('my data'.encode('utf-8')).decode('utf-8')
payload = json.dumps({'plaintext': plaintext_b64})
my_response = my_func(payload)

关键说明

  • base64.b64encode()接收bytes输入,返回bytes类型的Base64编码结果,必须用.decode('utf-8')转成字符串,满足“文本格式”的要求。
  • 避免直接传递未处理的bytes类型,同时要区分字典参数和JSON字符串参数的差异,根据my_func的实际参数要求选择对应传递方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 12:07:10