2

Using C client library (libmosquitto)

How to publish this json string to MQTT mosquitto broker

"book":[

    {"Name":"xyz", "price":"5.00"},
    {"Name":"abc", "price":"10.00"},
    {"Name":"hello world", "price":"15.00"}
]}

using this function.

    mosquitto_publish(mosq, NULL, "xyz", 10, "5.00", 2, false);

int mosquitto_publish(  mosq, mid, topic, payloadlen, payload, qos, retain);
Vin
  • 10,517
  • 10
  • 58
  • 71
marvic
  • 31
  • 2
  • 8

1 Answers1

0

Late reply but you'd do like so:

 #include <json-c/json.h>

 json_object *jobjr = json_object_new_object();
 json_object *jattr = json_object_new_object();

 json_object *jid = json_object_new_string(id);
 json_object_object_add(jattr, "id", jid);

 json_object_object_add(jobjr, "report", jattr);

 const char *report = json_object_to_json_string(jobjr);
 mosquitto_publish(mosq, 0, options.status_topic, strlen(report), report, 1, false);

 json_object_put(jobjr);

The key is to convert the JSON object to a string using json_object_to_json_string. That's if you're using libjson of course.

simonmorley
  • 2,810
  • 4
  • 30
  • 61