没有JSON对象可以使用python解码

时间:2014-02-04 17:33:51

标签: python json sockets

我的客户端中有以下代码:

        data = {"method": 2,"read": 3}
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect(server_address)
        req = json.dumps(data)
        s.send(req)

我正在服务器中尝试以下操作:

        # Threat the socket as a file stream.
        worker = self.conn.makefile(mode="rw")
        # Read the request in a serialized form (JSON).
        request = worker.readline()
        result = json.loads(request)
        print(result)

我收到No JSON object could be decoded错误。我正在使用python 3.3。我无法理解我的错误在哪里,似乎send方法不发送json对象。有什么想法吗?

Edit:我修复了JSON格式,现在问题是服务器上的<class 'TypeError'>: unsupported operand type(s) for +: 'NoneType' and 'str'和客户端上的s.send(req) TypeError: 'str' does not support the buffer interface

3 个答案:

答案 0 :(得分:1)

我假设您正在使用python 3,从错误判断。

您需要将数据编码为字节。套接字不能直接发送python3字符串。

答案 1 :(得分:0)

您的JSON无效。通过JSON lint来查找错误。 http://jsonlint.com/

答案 2 :(得分:0)

因为不是有效的JSON。

您可以查看json.org获取完整规范,并始终使用JSONlint来检查您的JSON。

JSON由键/值对组成。键始终是字符串,必须加双引号。不引用数字值。

{"method":2, "2":3}

由于OP更改问题而进行编辑:以上仅显示有效的 JSON ...您当然需要将其作为字符串在你的程序中用它做任何事情(比如通过套接字发送)。

data = '{"method": 2,"read": 3}'