How to send a json object using tcp socket in python How to send a json object using tcp socket in python json json

How to send a json object using tcp socket in python


Skip the json.loads() part. Send the json object as the json string and load it from the string at the TCP client.

Also check: Python sending dictionary throught TCP


Sending a dict with json like below worked in my program.

import socketimport sysimport jsonHOST, PORT = "localhost", 9999#m ='{"id": 2, "name": "abc"}'m = {"id": 2, "name": "abc"} # a real dict.data = json.dumps(m)# Create a socket (SOCK_STREAM means a TCP socket)sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)try:    # Connect to server and send data    sock.connect((HOST, PORT))    sock.sendall(bytes(data,encoding="utf-8"))    # Receive data from the server and shut down    received = sock.recv(1024)    received = received.decode("utf-8")finally:    sock.close()print "Sent:     {}".format(data)print "Received: {}".format(received)


AS you can find out from Python sending dictionary through TCPit better convert the JSON object to a dictionary and using the following snippet

import jsondata = json.load(open("data.json")) //or data = json.load('{"id": 2, "name": "abc"}')type(data)print(data[<keyFromTheJsonFile>])

You should serialize it with pickle:

import pickledict = {...}tcp_send(pickle.dumps(dict))

And on the other end:

import pickledict = pickle.loads(tcp_recieve())

If the other end is not written in python, you can use a data serialization format, like xml, json or yaml.