Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: encoding without string argument

Tags:

python

I can't see the problem

Hi, I have this function that converts a JSON dictionary to bytes. It then separates each element with b'\x00\x00'. I am doing this so that It can talk with a client I made for a game in Game Maker.

To better illustrate my problem I am going to use an example.This is the function that I am running Encode({"header": 1}).

Result I want b'header\x00\x001\x00\x00'

What I get TypeError: encoding without a string argument.

What I have tried

I have tried debugging this on my own, but I just can't seem to find the problem at hand. One thing that I find odd is that if I put this line from my code in a print ( This is also the part that is causing issues). It works print(buffer + bytes(_e,"utf-8") + b'\x00\x00') but this does not buffer = buffer + bytes(_e,"utf-8") + b'\x00\x00'.

Code

# Encode function
def Encode(data):
    buffer = b''
    for e in data.items():
        for _e in e:
            buffer = buffer + bytes(_e,"utf-8") + b'\x00\x00'
    return buffer
like image 652
Mr Ikea Avatar asked Mar 10 '26 10:03

Mr Ikea


1 Answers

You need to modify your code in order to get each pair of key-values and convert them to bytes. Keep in mind that you need to convert each value to string using str(), before you convert them to bytes:

# Encode function
def Encode(data):
    buffer = b''
    for key, value in data.items():
        buffer = buffer + bytes(key, 'utf-8') + b'\x00\x00' + bytes(str(value), 'utf-8') + b'\x00\x00'
    return buffer

r = Encode({"header": 1})
print(r)

This will return:

b'header\x00\x001\x00\x00'
like image 169
Vasilis G. Avatar answered Mar 13 '26 01:03

Vasilis G.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!