Durch die Nutzung von AWS re:Post stimmt du den AWS re:Post Nutzungsbedingungen

Send JSON documents with the pubsub.py sample app - MQTT Test Client displays string not json

0

Hi, I am new to AWS IoT and working through the SDK tutorials. Using RPi3B and python. https://docs.aws.amazon.com/iot/latest/developerguide/sdk-tutorials.html - I am @ "publish JSON documents in the message payload". I created pubsub3.py & changed the line of code: ...message = "{}".format(message_string). Tutorial says to 'change this line of code' to... message = "{}".format(args.message) BUT my pubsub.py has .format(message_string) var instead. The MQTT Test client is displaying as string literal and not interpreting/formatting correctly in json format. I have tried all sorts of combinations of quotes and breaks and brackets (" \ ' { ] ). From what I see it should be sending the payload as a json string...

Command line: pi3@raspberrypi:~ $ python3 aws-iot-device-sdk-python-v2/samples/pubsub3.py --message '{"temperature":40}' --count 1 --topic pi3/battery1/data --endpoint...


pubsub3.py: message = "{}".format(message_string) print("Publishing message to topic '{}': {}".format(message_topic, message)) message_json = json.dumps(message) mqtt_connection.publish( topic=message_topic, payload=message_json, qos=mqtt.QoS.AT_LEAST_ONCE) time.sleep(1)


Terminal: Sending 1 message(s) Publishing message to topic 'pi3/battery1/data': {"temperature":40} Received message from topic 'pi3/battery1/data': b'"{\"temperature\":40}"'


MQTT Test Client: pi3/battery1/data December 01, 2022, 11:59:52 (UTC-0500)

"{temperature: 40}"

If someone could offer me some assistance I would be very grateful!

gefragt vor 2 Jahren411 Aufrufe
1 Antwort
0
Akzeptierte Antwort

Hi,

Your message is already a string encoded JSON which is what the publish() methods expects.

Try replacing the line

message_json = json.dumps(message) 

with

message_json = message

Cheers,

Massimiliano

AWS
EXPERTE
beantwortet vor 2 Jahren
  • That was the fix needed...Thanks so much!

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.

Richtlinien für die Beantwortung von Fragen