json - 如何解决 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)
解决方案
我发现了我使用以下函数 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)
推荐阅读
- java - 在输入中为 char 设置异常以退出仅接受整数且不停止的程序
- mysql - 根据时间戳计算和更新当前行和最后一行之间的功耗
- python - Python:从包含表达式的字符串动态初始化类成员
- spring-integration - 如何在 spring-integration 中上传文件?
- firebase - 如何在 Google Cloud Build 上部署带有 env vars 的 Vue.js 应用程序?
- asp.net-mvc - 提交表单时更新数据库中的多行
- amazon-web-services - AWS Glue 作业在写入 S3 时被拒绝访问
- php - pgsql:在 PHP 中选择时区的数据
- sql - 如何使用sql递归编写公式
- python - 如何有效地从 mysql 写入和读取 numric (float, numpy) 数组?