这是我的python tcp客户端。我想将一个json对象发送到server.But我不能使用sendall()方法发送对象。我怎么能这样做?
import socket
import sys
import json
HOST, PORT = "localhost", 9999
m ='{"id": 2, "name": "abc"}'
jsonObj = json.loads(m)
data = jsonObj
# 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(jsonObj)
# Receive data from the server and shut down
received = sock.recv(1024)
finally:
sock.close()
print "Sent: {}".format(data)
print "Received: {}".format(received)
答案 0 :(得分:4)
略过json.loads()
部分。将json对象作为json字符串发送,并从TCP客户端的字符串加载它。
答案 1 :(得分:3)
使用以下代码发送带有json的字典在我的程序中有效。
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)
答案 2 :(得分:1)
您可以从Python sending dictionary through TCP找到答案 它最好将JSON对象转换为字典并使用以下代码段
import json
data = json.load(open("data.json"))
//or
data = json.load('{"id": 2, "name": "abc"}')
type(data)
print(data[<keyFromTheJsonFile>])
您应该使用pickle
序列化它:
import pickle
dict = {...}
tcp_send(pickle.dumps(dict))
另一方面:
import pickle
dict = pickle.loads(tcp_recieve())