skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    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 )
    

  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search