ValueError:无法将JSON对象解码为MQTT Python

时间:2018-09-12 09:28:39

标签: python json mqtt

在任何人链接另一个类似的问题之前,我已经仔细阅读了这里的问题,但结果都无法解决我的代码或对我的代码进行不正确的修正。

下面的代码在解码我的json字符串时遇到问题,不确定是否正确配置了字符串,或者是否错误编写了下面提供的完整代码(如果还有其他需要解决的麻烦,请告诉我)。

从经纪人处收到的字符串

test 0 $GPRP,7F82854A6A62,C3D7EDB7EF28,-65,0201061AFF4C0002158A174208F78D495E8FDA176A3FC0F34D00160019BD

python代码

# Open database connection
db = MySQLdb.connect(mysql_server, mysql_username, mysql_passwd, mysql_db)
# prepare a cursor object using cursor() method
cursor = db.cursor()

def on_connect(self,mosq, obj, rc):
    print("rc: "+str(rc))

def on_message(mosq, obj, msg):
    print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
    vars_to_sql = []
    keys_to_sql = []
    list = []

    list = json.loads(msg.payload)

    for key,value in list.iteritems():
      print ("")
      print key, value
      if key == 'tst':
        print "time found"
        print value
        value = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(float(value)))
    print value

  value_type = type(value)
  if value_type is not dict:
    print "value_type is not dict"
    if value_type is unicode:
      print "value_type is unicode"
      vars_to_sql.append(value.encode('ascii', 'ignore'))
      keys_to_sql.append(key.encode('ascii', 'ignore'))
    else:
      print "value_type is not unicode"
      vars_to_sql.append(value)
      keys_to_sql.append(key)
#add the msg.topic to the list as well
print "topic", msg.topic
addtopic = 'topic'
vars_to_sql.append(msg.topic.encode('ascii', 'ignore'))
keys_to_sql.append(addtopic.encode('ascii', 'ignore'))

keys_to_sql = ', '.join(keys_to_sql)

try:
   # Execute the SQL command 
   # change locations to the table you are using
   queryText = "INSERT INTO messages(%s) VALUES %r"
   queryArgs = (keys_to_sql, tuple(vars_to_sql))
   cursor.execute(queryText % queryArgs)
   print('Successfully Added record to mysql')
   db.commit()
except MySQLdb.Error, e:
    try:
        print "MySQL Error [%d]: %s" % (e.args[0], e.args[1])
    except IndexError:
        print "MySQL Error: %s" % str(e)
    # Rollback in case there is any error
    db.rollback()
    print('ERROR adding record to MYSQL')

def on_publish(mosq, obj, mid):
print("mid: "+str(mid))

def on_subscribe(mosq, obj, mid, granted_qos):
print("Subscribed: "+str(mid)+" "+str(granted_qos))

def on_log(mosq, obj, level, string):
print(string)

mqttc = paho.Client()
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
# Uncomment to enable debug messages
mqttc.on_log = on_log

mqttc.connect(broker, broker_port, 60)
mqttc.subscribe(broker_topic, 0)

rc = 0
while rc == 0:
rc = mqttc.loop()

print("rc: "+str(rc))

1 个答案:

答案 0 :(得分:1)

假设问题出在线路上

list = json.loads(msg.payload)

on_message()回调中,而msg.payload是:

$GPRP,7F82854A6A62,C3D7EDB7EF28,-65,0201061AFF4C0002158A174208F78D495E8FDA176A3FC0F34D00160019BD

然后将失败,因为有效负载不是JSON对象。 json.loads()将不知道如何处理。

这是一个基本的CSV字符串,您应该能够使用split()函数将其分解为各个组件,然后必须根据规范来解释每个组件。