首页 > 解决方案 > 如何解决 Ubuntu 中的 Json 解码错误

问题描述

我在 Window 10 上运行 python 脚本。在 python 脚本中,我使用的是 json 库。当我在 Ubuntu 20.04(在 VMware 上运行)上运行相同的脚本时,我确实看到发生了 json decode 错误。我在 Windows 10 中运行时看不到这种行为。

以下是我在 Ubuntu 中运行脚本时遇到的错误

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.8/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "uiControl.py", line 83, in getTcpData
    self.taskObj = json.loads(data.decode('utf-8'))
  File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.8/json/decoder.py", line 340, in decode
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 5 column 2 (char 73)

在函数 on_message 中,我正在打印接收到的数据。以下是我收到的数据: b'{"code":"101","user":"ssmr","evNumber":"TS15EC1100"}'

我调用函数 addToTaskQueue() 来存储接收到的数据,然后尝试使用函数 BackendParser() 解析数据

def on_message(self,client, userdata, msg):
    print(msg.payload)
    self.taskObj = json.loads(msg.payload )
    self.taskObj["commType"]= "mqtt"
    self.taskObj["transactionType"]= "rx"        
    taskScheduler.addToTaskQueue(self.taskObj)

def BackendParser(msg):
    if(msg["code"] == "101"):
        Backend.userName = msg["user"]
        Backend.evNumber = msg["evNumber"]
        Backend.evChargeControl = "On"
        if(Backend.requestStatus == ""):
            Backend.requestStatus = "new"


class taskScheduler():
    global qTaskList

    qTaskList = queue.Queue()     
    def __init__(self):
        super().__init__()
        self.tcpCon = tcpServerClient("client")
        self.mqttCon = mqttComm()
        print("Initiated Task Scheduler class")

    @staticmethod
    def addToTaskQueue(item):
        if not qTaskList.full():
            #print("Task added")
            qTaskList.put(item)

    def executeFromTaskQueue(self):
        if not qTaskList.empty():
            item = qTaskList.get()
            if("mqtt" == item["commType"]):
                if("tx" == item["transactionType"]):
                    pubTopic = item["topic"]
                    del item["commType"]
                    del item["transactionType"]
                    del item["topic"]
                    self.mqttCon.mqttSend(item,pubTopic)
                elif("rx" == item["transactionType"]):
                    BackendParser(item)
            elif("tcp" == item["commType"]):
                if("tx" == item["transactionType"]):
                    del item["commType"]
                    del item["transactionType"]
                    tcpServerClient.sendTcpData(item)
                elif("rx" == item["transactionType"]):
                    BackendParser(item)

标签: jsonpython-3.xwindowsubuntu

解决方案


我发现了我使用以下函数 getTcpData 接收数据的错误。我尝试打印收到的数据,并注意到收到的消息中有 \n 字符。在 Windows 10 中执行脚本时,这不是问题。我现在添加了删除 \n 字符的例程,现在它在Ubuntu。

def getTcpData(self):  
    print("Waiting for tcp data")
    while True:
        if(tcpServerClient.clientsocket != None):
            data=tcpServerClient.clientsocket.recv(1024)
            if data:
                print(data)
                self.taskObj = json.loads(data.decode('utf-8'))
                self.taskObj["commType"]= "tcp"
                self.taskObj["transactionType"]= "rx"
                taskScheduler.addToTaskQueue(self.taskObj)

推荐阅读