套接字上的json字符串

时间:2018-07-26 17:24:09

标签: python json

我是json使用的新手,我需要按照给定的方式发送“数据”,

import json, socket

data = '{"command":"off"}'

_send(socket, data)

def _send(socket, data):
   try:
       serialized = json.dumps(data).replace('\\','')
   except (TypeError, ValueError) as e:
      raise Exception('You can only send JSON-serializable data')
  # send the length of the serialized data first
  socket.send(('%d\n' % len(serialized)))
  # send the serialized data
  socket.sendall(serialized)#.encode('utf-8'))

在服务器上,我需要以下数据,

{"command":"off"}

但是服务器收到的数据如下,

"{"command":"off"}"20

如何删除其他字符串。

1 个答案:

答案 0 :(得分:0)

您的数据是一个字符串,但是服务器需要一个对象。尝试向它发送一个对象。

data = {"command":"off"} # note this is a python dictionary

def _send(socket, data):
   try:
       serialized = json.dumps(data) # no stripping necessary
   except (TypeError, ValueError) as e:
    ...

此行是红色标记json.dumps(data).replace('\\',''),通常表示您在编码对象时不小心对字符串进行了编码。