Python 3 Paho-MQTT Published/Subscribed JSON message won't parse












0















Rookie here.



I have a simple python code that's supposed to subscribe to a topic and publish JSON payload to the same topic using MQTT protocol. But for some reason, I am unable to load the payload as JSON!



What am I doing wrong here?



# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import json
mqtt_broker = '192.168.1.111'
mqtt_topic_one = 'mqtt_topic/tops_one'
mqtt_topic_two = 'mqtt_topic/tops_two'

json_data_1 = '''{
"this_json": "info",
"data": {
"multi_keyval": {
"1": "1",
"5": "5",
"15": "15"
},
"single_keyval": {
"single_key": "200"
}
}
}'''


def pass_to_func_and_pub(data_to_pub):
print(data_to_pub) # --------> This PRINTS
print(json.loads(data_to_pub)) # --------> This DOES NOT PRINT

# The following two lines don't work either.
unpacked_json = json.loads(data_to_pub)
client.publish(mqtt_topic_two, unpacked_json['this_json'])


def on_connect(client, userdata, flags, rc):
client.subscribe(mqtt_topic_one)
client.publish(mqtt_topic_one, json_data_1)


def on_message(client, userdata, msg):
pass_to_func_and_pub(str(msg.payload))

client = mqtt.Client()

client.on_connect = on_connect
client.on_message = on_message

client.connect(mqtt_broker)
try:
client.loop_forever()
except KeyboardInterrupt:
client.disconnect()
print('MQTT client disconnected, exiting now.')









share|improve this question



























    0















    Rookie here.



    I have a simple python code that's supposed to subscribe to a topic and publish JSON payload to the same topic using MQTT protocol. But for some reason, I am unable to load the payload as JSON!



    What am I doing wrong here?



    # -*- coding: utf-8 -*-
    import paho.mqtt.client as mqtt
    import json
    mqtt_broker = '192.168.1.111'
    mqtt_topic_one = 'mqtt_topic/tops_one'
    mqtt_topic_two = 'mqtt_topic/tops_two'

    json_data_1 = '''{
    "this_json": "info",
    "data": {
    "multi_keyval": {
    "1": "1",
    "5": "5",
    "15": "15"
    },
    "single_keyval": {
    "single_key": "200"
    }
    }
    }'''


    def pass_to_func_and_pub(data_to_pub):
    print(data_to_pub) # --------> This PRINTS
    print(json.loads(data_to_pub)) # --------> This DOES NOT PRINT

    # The following two lines don't work either.
    unpacked_json = json.loads(data_to_pub)
    client.publish(mqtt_topic_two, unpacked_json['this_json'])


    def on_connect(client, userdata, flags, rc):
    client.subscribe(mqtt_topic_one)
    client.publish(mqtt_topic_one, json_data_1)


    def on_message(client, userdata, msg):
    pass_to_func_and_pub(str(msg.payload))

    client = mqtt.Client()

    client.on_connect = on_connect
    client.on_message = on_message

    client.connect(mqtt_broker)
    try:
    client.loop_forever()
    except KeyboardInterrupt:
    client.disconnect()
    print('MQTT client disconnected, exiting now.')









    share|improve this question

























      0












      0








      0








      Rookie here.



      I have a simple python code that's supposed to subscribe to a topic and publish JSON payload to the same topic using MQTT protocol. But for some reason, I am unable to load the payload as JSON!



      What am I doing wrong here?



      # -*- coding: utf-8 -*-
      import paho.mqtt.client as mqtt
      import json
      mqtt_broker = '192.168.1.111'
      mqtt_topic_one = 'mqtt_topic/tops_one'
      mqtt_topic_two = 'mqtt_topic/tops_two'

      json_data_1 = '''{
      "this_json": "info",
      "data": {
      "multi_keyval": {
      "1": "1",
      "5": "5",
      "15": "15"
      },
      "single_keyval": {
      "single_key": "200"
      }
      }
      }'''


      def pass_to_func_and_pub(data_to_pub):
      print(data_to_pub) # --------> This PRINTS
      print(json.loads(data_to_pub)) # --------> This DOES NOT PRINT

      # The following two lines don't work either.
      unpacked_json = json.loads(data_to_pub)
      client.publish(mqtt_topic_two, unpacked_json['this_json'])


      def on_connect(client, userdata, flags, rc):
      client.subscribe(mqtt_topic_one)
      client.publish(mqtt_topic_one, json_data_1)


      def on_message(client, userdata, msg):
      pass_to_func_and_pub(str(msg.payload))

      client = mqtt.Client()

      client.on_connect = on_connect
      client.on_message = on_message

      client.connect(mqtt_broker)
      try:
      client.loop_forever()
      except KeyboardInterrupt:
      client.disconnect()
      print('MQTT client disconnected, exiting now.')









      share|improve this question














      Rookie here.



      I have a simple python code that's supposed to subscribe to a topic and publish JSON payload to the same topic using MQTT protocol. But for some reason, I am unable to load the payload as JSON!



      What am I doing wrong here?



      # -*- coding: utf-8 -*-
      import paho.mqtt.client as mqtt
      import json
      mqtt_broker = '192.168.1.111'
      mqtt_topic_one = 'mqtt_topic/tops_one'
      mqtt_topic_two = 'mqtt_topic/tops_two'

      json_data_1 = '''{
      "this_json": "info",
      "data": {
      "multi_keyval": {
      "1": "1",
      "5": "5",
      "15": "15"
      },
      "single_keyval": {
      "single_key": "200"
      }
      }
      }'''


      def pass_to_func_and_pub(data_to_pub):
      print(data_to_pub) # --------> This PRINTS
      print(json.loads(data_to_pub)) # --------> This DOES NOT PRINT

      # The following two lines don't work either.
      unpacked_json = json.loads(data_to_pub)
      client.publish(mqtt_topic_two, unpacked_json['this_json'])


      def on_connect(client, userdata, flags, rc):
      client.subscribe(mqtt_topic_one)
      client.publish(mqtt_topic_one, json_data_1)


      def on_message(client, userdata, msg):
      pass_to_func_and_pub(str(msg.payload))

      client = mqtt.Client()

      client.on_connect = on_connect
      client.on_message = on_message

      client.connect(mqtt_broker)
      try:
      client.loop_forever()
      except KeyboardInterrupt:
      client.disconnect()
      print('MQTT client disconnected, exiting now.')






      python json python-3.x mqtt paho






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 16 '18 at 8:58









      bipsterbipster

      6418




      6418
























          1 Answer
          1






          active

          oldest

          votes


















          3














          There are a couple of problems here.



          1. Exception handling



          You're not handling exceptions (and Paho effectively ignores them within handlers, to keep the client alive I guess). This means when the exception is thrown in json.loads(data_to_pub), you're never seeing this but the function is exited as there is no local except block.



          Improved version



          def pass_to_func_and_pub(data_to_pub):
          print("Raw data: ", data_to_pub)
          try:
          unpacked_json = json.loads(data_to_pub)
          except Exception as e:
          print("Couldn't parse raw data: %s" % data_to_pub, e)
          else:
          print("JSON:", unpacked_json)
          client.publish(mqtt_topic_two, unpacked_json['this_json'])


          Hang on, what exception?



          Running this improved version we can now see:



          Couldn't parse raw data: b'{n "this_json": "info",n "data": {n "multi_keyval": {n "1": "1",n "5": "5",n "15": "15"n },n "single_keyval": {n "single_key": "200"n }n }n}' Expecting value: line 1 column 1 (char 0)



          Hmmm, what's that b' doing there?...



          2. The encoding problem



          Essentially your problem comes down to one line



          def on_message(client, userdata, msg):
          pass_to_func_and_pub(str(msg.payload))


          By calling str on the payload of that MqttMessage, which is a bytes object in Python 3, you'll get the stringified version of those bytes, e.g. b'foobar'.



          This b, of course, makes it invalid JSON now, hence Expecting value: line 1 column 1 (char 0)...



          Fixed version



          Don't call str! Json.loads can handle bytes too. So:



          def on_message(client, userdata, msg):
          pass_to_func_and_pub(msg.payload)


          Or, assuming utf-8 encoding, we can do this more explicitly (I prefer working in strings):



          def on_message(client, userdata, msg):
          pass_to_func_and_pub(msg.payload.decode('utf-8'))


          Hope that helps!






          share|improve this answer
























          • This is answer's wonderful and worked perfectly! Thank you so much. I didn't realize that Paho ignores exceptions within handlers.

            – bipster
            Nov 16 '18 at 12:44













          • Great! Glad it helped

            – declension
            Nov 16 '18 at 14:15












          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53334451%2fpython-3-paho-mqtt-published-subscribed-json-message-wont-parse%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          3














          There are a couple of problems here.



          1. Exception handling



          You're not handling exceptions (and Paho effectively ignores them within handlers, to keep the client alive I guess). This means when the exception is thrown in json.loads(data_to_pub), you're never seeing this but the function is exited as there is no local except block.



          Improved version



          def pass_to_func_and_pub(data_to_pub):
          print("Raw data: ", data_to_pub)
          try:
          unpacked_json = json.loads(data_to_pub)
          except Exception as e:
          print("Couldn't parse raw data: %s" % data_to_pub, e)
          else:
          print("JSON:", unpacked_json)
          client.publish(mqtt_topic_two, unpacked_json['this_json'])


          Hang on, what exception?



          Running this improved version we can now see:



          Couldn't parse raw data: b'{n "this_json": "info",n "data": {n "multi_keyval": {n "1": "1",n "5": "5",n "15": "15"n },n "single_keyval": {n "single_key": "200"n }n }n}' Expecting value: line 1 column 1 (char 0)



          Hmmm, what's that b' doing there?...



          2. The encoding problem



          Essentially your problem comes down to one line



          def on_message(client, userdata, msg):
          pass_to_func_and_pub(str(msg.payload))


          By calling str on the payload of that MqttMessage, which is a bytes object in Python 3, you'll get the stringified version of those bytes, e.g. b'foobar'.



          This b, of course, makes it invalid JSON now, hence Expecting value: line 1 column 1 (char 0)...



          Fixed version



          Don't call str! Json.loads can handle bytes too. So:



          def on_message(client, userdata, msg):
          pass_to_func_and_pub(msg.payload)


          Or, assuming utf-8 encoding, we can do this more explicitly (I prefer working in strings):



          def on_message(client, userdata, msg):
          pass_to_func_and_pub(msg.payload.decode('utf-8'))


          Hope that helps!






          share|improve this answer
























          • This is answer's wonderful and worked perfectly! Thank you so much. I didn't realize that Paho ignores exceptions within handlers.

            – bipster
            Nov 16 '18 at 12:44













          • Great! Glad it helped

            – declension
            Nov 16 '18 at 14:15
















          3














          There are a couple of problems here.



          1. Exception handling



          You're not handling exceptions (and Paho effectively ignores them within handlers, to keep the client alive I guess). This means when the exception is thrown in json.loads(data_to_pub), you're never seeing this but the function is exited as there is no local except block.



          Improved version



          def pass_to_func_and_pub(data_to_pub):
          print("Raw data: ", data_to_pub)
          try:
          unpacked_json = json.loads(data_to_pub)
          except Exception as e:
          print("Couldn't parse raw data: %s" % data_to_pub, e)
          else:
          print("JSON:", unpacked_json)
          client.publish(mqtt_topic_two, unpacked_json['this_json'])


          Hang on, what exception?



          Running this improved version we can now see:



          Couldn't parse raw data: b'{n "this_json": "info",n "data": {n "multi_keyval": {n "1": "1",n "5": "5",n "15": "15"n },n "single_keyval": {n "single_key": "200"n }n }n}' Expecting value: line 1 column 1 (char 0)



          Hmmm, what's that b' doing there?...



          2. The encoding problem



          Essentially your problem comes down to one line



          def on_message(client, userdata, msg):
          pass_to_func_and_pub(str(msg.payload))


          By calling str on the payload of that MqttMessage, which is a bytes object in Python 3, you'll get the stringified version of those bytes, e.g. b'foobar'.



          This b, of course, makes it invalid JSON now, hence Expecting value: line 1 column 1 (char 0)...



          Fixed version



          Don't call str! Json.loads can handle bytes too. So:



          def on_message(client, userdata, msg):
          pass_to_func_and_pub(msg.payload)


          Or, assuming utf-8 encoding, we can do this more explicitly (I prefer working in strings):



          def on_message(client, userdata, msg):
          pass_to_func_and_pub(msg.payload.decode('utf-8'))


          Hope that helps!






          share|improve this answer
























          • This is answer's wonderful and worked perfectly! Thank you so much. I didn't realize that Paho ignores exceptions within handlers.

            – bipster
            Nov 16 '18 at 12:44













          • Great! Glad it helped

            – declension
            Nov 16 '18 at 14:15














          3












          3








          3







          There are a couple of problems here.



          1. Exception handling



          You're not handling exceptions (and Paho effectively ignores them within handlers, to keep the client alive I guess). This means when the exception is thrown in json.loads(data_to_pub), you're never seeing this but the function is exited as there is no local except block.



          Improved version



          def pass_to_func_and_pub(data_to_pub):
          print("Raw data: ", data_to_pub)
          try:
          unpacked_json = json.loads(data_to_pub)
          except Exception as e:
          print("Couldn't parse raw data: %s" % data_to_pub, e)
          else:
          print("JSON:", unpacked_json)
          client.publish(mqtt_topic_two, unpacked_json['this_json'])


          Hang on, what exception?



          Running this improved version we can now see:



          Couldn't parse raw data: b'{n "this_json": "info",n "data": {n "multi_keyval": {n "1": "1",n "5": "5",n "15": "15"n },n "single_keyval": {n "single_key": "200"n }n }n}' Expecting value: line 1 column 1 (char 0)



          Hmmm, what's that b' doing there?...



          2. The encoding problem



          Essentially your problem comes down to one line



          def on_message(client, userdata, msg):
          pass_to_func_and_pub(str(msg.payload))


          By calling str on the payload of that MqttMessage, which is a bytes object in Python 3, you'll get the stringified version of those bytes, e.g. b'foobar'.



          This b, of course, makes it invalid JSON now, hence Expecting value: line 1 column 1 (char 0)...



          Fixed version



          Don't call str! Json.loads can handle bytes too. So:



          def on_message(client, userdata, msg):
          pass_to_func_and_pub(msg.payload)


          Or, assuming utf-8 encoding, we can do this more explicitly (I prefer working in strings):



          def on_message(client, userdata, msg):
          pass_to_func_and_pub(msg.payload.decode('utf-8'))


          Hope that helps!






          share|improve this answer













          There are a couple of problems here.



          1. Exception handling



          You're not handling exceptions (and Paho effectively ignores them within handlers, to keep the client alive I guess). This means when the exception is thrown in json.loads(data_to_pub), you're never seeing this but the function is exited as there is no local except block.



          Improved version



          def pass_to_func_and_pub(data_to_pub):
          print("Raw data: ", data_to_pub)
          try:
          unpacked_json = json.loads(data_to_pub)
          except Exception as e:
          print("Couldn't parse raw data: %s" % data_to_pub, e)
          else:
          print("JSON:", unpacked_json)
          client.publish(mqtt_topic_two, unpacked_json['this_json'])


          Hang on, what exception?



          Running this improved version we can now see:



          Couldn't parse raw data: b'{n "this_json": "info",n "data": {n "multi_keyval": {n "1": "1",n "5": "5",n "15": "15"n },n "single_keyval": {n "single_key": "200"n }n }n}' Expecting value: line 1 column 1 (char 0)



          Hmmm, what's that b' doing there?...



          2. The encoding problem



          Essentially your problem comes down to one line



          def on_message(client, userdata, msg):
          pass_to_func_and_pub(str(msg.payload))


          By calling str on the payload of that MqttMessage, which is a bytes object in Python 3, you'll get the stringified version of those bytes, e.g. b'foobar'.



          This b, of course, makes it invalid JSON now, hence Expecting value: line 1 column 1 (char 0)...



          Fixed version



          Don't call str! Json.loads can handle bytes too. So:



          def on_message(client, userdata, msg):
          pass_to_func_and_pub(msg.payload)


          Or, assuming utf-8 encoding, we can do this more explicitly (I prefer working in strings):



          def on_message(client, userdata, msg):
          pass_to_func_and_pub(msg.payload.decode('utf-8'))


          Hope that helps!







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 16 '18 at 9:45









          declensiondeclension

          3,1391420




          3,1391420













          • This is answer's wonderful and worked perfectly! Thank you so much. I didn't realize that Paho ignores exceptions within handlers.

            – bipster
            Nov 16 '18 at 12:44













          • Great! Glad it helped

            – declension
            Nov 16 '18 at 14:15



















          • This is answer's wonderful and worked perfectly! Thank you so much. I didn't realize that Paho ignores exceptions within handlers.

            – bipster
            Nov 16 '18 at 12:44













          • Great! Glad it helped

            – declension
            Nov 16 '18 at 14:15

















          This is answer's wonderful and worked perfectly! Thank you so much. I didn't realize that Paho ignores exceptions within handlers.

          – bipster
          Nov 16 '18 at 12:44







          This is answer's wonderful and worked perfectly! Thank you so much. I didn't realize that Paho ignores exceptions within handlers.

          – bipster
          Nov 16 '18 at 12:44















          Great! Glad it helped

          – declension
          Nov 16 '18 at 14:15





          Great! Glad it helped

          – declension
          Nov 16 '18 at 14:15




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53334451%2fpython-3-paho-mqtt-published-subscribed-json-message-wont-parse%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Xamarin.iOS Cant Deploy on Iphone

          Glorious Revolution

          Dulmage-Mendelsohn matrix decomposition in Python