close

How to send a json object using tcp socket in python

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to send a json object using tcp socket in python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

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

  1. 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.

  2. 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.

Method 1

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

import socket
import sys
import json

HOST, 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)

Method 2

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

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read