Question about using Variant to publish data

Hi,

I’m not sure if this is the right category so please correct me if wrong

I was following the tutorial for DataCake and found it used Variant class - this looks like it is a great way to package data for publishing. So to check it out i have played with the simplest of code - see below. However, both log.info serial output, and looking at events for this device show a different order of tag and data than it was constructed - what am I missing

Thanks for any help

Paul

// code snip

void publishCounter()
{
particle::Variant obj;
obj.set("counter", globalCount);
obj.set("timestamp", millis());
obj.set("bool", myBoolean);
obj.set("int", myInt);
obj.set("float", myFloat);
obj.set("string", myString);

event.name("datacake-pump-data");
event.data(obj);
Particle.publish(event);

Log.info("publishing %s", obj.toJSON().c_str());
}

// Log.info output

0001695028 [app] INFO: publishing {"bool":true,"counter":15,"float":3.1415,"int":1,"string":"Hello world!","timestamp":1695023}
0001695190 [app] INFO: publish succeeded
0001815028 [app] INFO: publishing {"bool":true,"counter":16,"float":3.1415,"int":1,"string":"Hello world!","timestamp":1815023}
0001815202 [app] INFO: publish succeeded

I like using the Variant class, too. I don’t know the answer to your question. Maybe someone will jump in with it.

What I did to perform a sort was to enter a sequence number as a prefix for the tag, like this:

obj.set("1_counter", globalCount);
obj.set("2_timestamp", millis());
obj.set("3_bool", myBoolean);
obj.set("4_int", myInt);
obj.set("5_float", myFloat);
obj.set("6_string", myString);

Hope this helps.

Thanks Rob,

While falling asleep I remember reading in the docs that is good at reducing the size - wonder if that’s why.

It works, and for me will makes coding for publishing easier - just want to make sure I’m not missing something.

The order of keys is not preserved in conversion between Variant, JSON, and CBOR. The purpose of using name/value pairs is so the order doesn't matter and you can add or remove fields without breaking parsing.