3

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
1
  • 1
    Great question! This is the quality question we like to see on StackOverflow! Keep up the good work :) Commented May 8, 2021 at 22:57

1 Answer 1

1

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'
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.