Python3 JsonDecodeError预期分隔符

时间:2018-07-18 01:55:38

标签: python json sockets

我正在尝试编写一个Python脚本,该脚本可以访问在Python3中工作的Cgminer RPC。

除了这一特定命令外,我已经可以使用它了。每当我运行它时,它都会返回以下内容:

  Traceback (most recent call last):
File "newapi.py", line 61, in <module>
  enc = json.loads(returned)
File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
  return _default_decoder.decode(s)
File "/usr/lib/python3.6/json/decoder.py", line 339, in decode
  obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.6/json/decoder.py", line 355, in raw_decode
  obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 222 (char 221)

我尝试了在其他答案中发现的多种方法,包括使用:

.replace('//' /r'//')

之类的,但没有替换代码可让json.loads解析文件。

这是我的原始代码:

import socket
import logging as log
import json
import sys
class CgminerAPI(object):
    """ Cgminer RPC API wrapper. """
    def __init__(self, host='192.168.86.31', port=4028):
        self.data = {}
        self.host = host
        self.port = port

    def command(self, command, arg=None):
        """ Initialize a socket connection,
        send a command (a json encoded dict) and
        receive the response (and decode it).
        """
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        try:
            log.debug("connecting to %s:%d", self.host, self.port)
            sock.connect((self.host, self.port))
        except (socket.error, e):
            log.error("unable to connect to %s:%d", self.host, self.port)
            sys.exit(1)

        try:
            payload = {"command": command}
            jspay = json.dumps(payload)
            encpay = jspay.encode('utf-8')
            if arg is not None:
                # Parameter must be converted to basestring (no int)
                payload.update({'parameter': unicode(arg)})

            sock.send(encpay)
            received = self._receive(sock)

        finally:
            sock.shutdown(socket.SHUT_RDWR)
            sock.close()

        return received

    def _receive(self, sock, size=4096):
        msg = ''
        while 1:
            chunk = sock.recv(size).decode('utf-8')
            if chunk:
                msg += chunk
            else:
                break
        return msg

    def __getattr__(self, attr):
        def out(arg=None):
            return self.command(attr, arg)
        return out

miner = CgminerAPI()
returned = (miner.command('stats'))
returned = returned.replace('\x00','')
enc = json.loads(returned)
print(enc)

0 个答案:

没有答案