英文:
TypeError: Object of type bytes is not JSON serializable on bytes stream
问题
我有以下代码摘录:
my_response = my_func(
plaintext='my data'.encode()))
)
这会引发TypeError:Object of type bytes is not JSON serializable异常,此外,如果我将其更改为:
my_response = my_func(
json.dumps(dict(plaintext='my data'.encode()))
)
我会得到:
TypeError: cannot convert dictionary update sequence element #0 to a sequence
请问有人能建议我如何修复这个问题,顺便说一句,我正在使用Python 3。
另外,我传递给my_func的参数需要以文本形式进行base64编码。
英文:
I have the following code excerpt:
my_response = my_func(
plaintext='my data'.encode()))
)
This throws a TypeError: Object of type bytes is not JSON serializable exception, also, if I change this to:
my_response = my_func(
json.dumps(dict(plaintext='my data'.encode()))
)
I get:
TypeError: cannot convert dictionary update sequence element #0 to a sequence
Can someone please advice as to how I can fix this, I'm using Python 3 BTW
Also, the argument I pass into my_func needs to be base64 encoded, but in text form.
答案1
得分: 0
问题明显出在调用.encode()
方法上。这会返回一个字节字符串,你不应该强制将其JSON序列化。所以,你需要使用decode
方法来“撤销”或“反转”这个操作。试试这样做:
my_response = my_func(
plaintext='my data'.encode().decode())
)
希望这解决了你的问题并对你有所帮助。
英文:
The problem is plainly calling the .encode()
method. This returns a byte string, which you should not force JSON serialize. So, you need to use the decode
method to "undo" or "reverse" this. Try this:
my_response = my_func(
plaintext='my data'.encode().decode()))
)
Hope this answers your problem and helps you.
答案2
得分: 0
我最终成功地让以下代码执行我想要的操作:
dataStr = b'some data'
base64_bytes = base64.b64encode(dataStr)
base64_message = base64_bytes.decode('ascii')
my_response = my_func( plaintext=base64_message )
英文:
I eventually managed to get the following code to do what I wanted:
dataStr = b'some data'
base64_bytes = base64.b64encode(dataStr)
base64_message = base64_bytes.decode('ascii')
my_response = my_func( plaintext=base64_message )
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论