python 2.7 socket communication with json

Viewed 100

I want to send/recv data through socket.

I use python 2.7 because of ROS(melodic) and also use python 3.6 because of tensorflow.

The dict data, for example {'key_name':[[1,2,3],[4,5,6]]}, is sent and encoded with JSONEncoder.encoder().
The Client received the json data with loads() and resend it to the Server.
The Client uses python 2.7 and the Server uses python 3.6

def _send(socket, send_data):
    json_data = json.JSONEncoder().encode(send_data)
    socket.sendall(json_data)

def _recv(socket):
    recv_data = socket.recv(BUFSIZE)
    json_data = json.loads(recv_data, encoding="utf-8")

    return json_data

I have the error

  File "/usr/lib/python3.6/json/deoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 4097 (char 4096)

I need a python code which runs on both python 2.7 and 3.6.

1 Answers

The error is coming from json decoder.

json_data = json.loads(recv_data, encoding="utf-8"),

It is expected when your json data ( in your case the recv_data) is not in proper format. Usually missing a comma ',' or something. For debugging I would suggest you to dump the data received at server, before going for json.loads()

Related