Ok, I figured it out π
For anyone interested, here goes the solution that worked for me:
#####
# json.dumps() takes a string, returns a string
# json.loads() takes a string, bytes or bytearray, returns string
# .encode() takes a string, return bytes
# .decode() takes bytes, returns a string
#####
so the simplified working version (just one message from host to client); This is the code after establishing connection:
<<HOST>>
msg = input(“>> “) #(msg is a STRING)
msg_json = json.dumps(msg) #msg_json is a (serialized) STRING
connection.send(msg_json.encode()) #since the socket.send() in Python3 requires bytes, we use the .encode() function –> sending BYTES
<<CLIENT>>
msg_json_encoded = connection.recv(1024) #we receive the json-formatted BYTES
***msg_json_encoded.decode()*** – this step is not necessary, explained below*
msg = json.loads(msg_json_encoded) #jason.loads() does all the magic
print(msg)
* This is what json.loads() does: “Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object” Therefore it can handle bytes, we don’t need to use .decode() first. Learned that by accident π
Ok, so not only does it work, it’s actually not that complicated π
Still, if I may, I would like to know if it’s “right”?
Meaning, is there a more elegant/efficient way of dealing with json and sockets in Python3?
Thanks, sorry again for all the trouble!