TypeError: 字节流的对象不可序列化为 JSON 格式。

huangapple go评论68阅读模式
英文:

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 )

huangapple
  • 本文由 发表于 2023年6月12日 18:13:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76455629.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定