user3690081
user3690081

Reputation: 215

How to Send data as JSON objects over to MQTT broker

I'm using eclipse paho client on ubuntu and trying to send latitude, longitude and timestamp information as JSON format to the MQTT broker. How do I do that?

I found this article, But its not complete.

Upvotes: 13

Views: 69844

Answers (3)

gurma
gurma

Reputation: 21

If you're using JavaScript, than you can use:

client.publish("foo", JSON.stringify({"foo": bar, "baz": 123})) // on sender side, and

JSON.parse on the receiver end.

Upvotes: 1

user5740843
user5740843

Reputation: 1620

I don't know about that, but I use his:

#!/usr/bin/python
import json
import paho.mqtt.client as mqtt


send_msg = {
        'data_to_send': variable1,
        'also_send_this': variable2
}

client.publish("topic", payload=json.dumps(send_msg), qos=2, retain=False)

Upvotes: 8

hardillb
hardillb

Reputation: 59638

You just need to create your JSON object as a string then call getBytes() on that string to get the byte array to use as your payload in the message.

 MqttMessage message = new MqttMessage();
 message.setPayload("{foo: bar, lat: 0.23443, long: 12.3453245}".getBytes());
 client.publish("foo", message);

Upvotes: 21

Related Questions