Unable to create valid JSON in Spark.publish() [SOLVED]

I am following the tutorial in the post below to publish JSON data from a Spark.publish() call and having an issue creating valid JSON.

The code on the core is as follows:

char json[100];
sprintf(json,"{\"temperature\": %f, \"humidity\": %f, \"lux\": %f}", temp, humidity, lux);
Spark.publish("nimbus", json, 60, PRIVATE);

When subscribing to this event I get the following data returned (via both CURL and node):

data: {"data":"{\"temperature\": 24.600000, \"humidity\": 53.500000, \"lux\": 13.321","ttl":"60","published_at":"2014-06-11T20:21:55.181Z","coreid":"xxx"}

The second curly bracket within the sprintf function is always missing which means it is not possible parse the JSON correctly. Any ideas why or where this would be stripped?

Tutorial post:

Hi @scottsweb

I think you are going over the 63-byte limit for Spark.publish() data. Can you try cutting down “temperature” to say "t’ and “humidity” to “h” and “lux” to “l”? You can also add formatting directives to control the number digits you are printing to have an appropriate number of significant digits.

The doc for publish is here:

http://docs.spark.io/firmware/#data-and-control-spark-publish

1 Like

@bko Looks like you are spot on with that. Shorter variable names have fixed the issue.

Can you explain a little more about the formatting directives and how I might go about trimming the sensor data to two decimal places.

Thanks for your help

Sure! With sprintf() you have C print formatting and you can control the total width for the number and for floating point numbers, the number of digits after the decimal point. So if we assume that temperature and humidity are the normal range, you could do this:

sprintf(json,"{\"t\": %6.2f, \"h\": %6.2f, \"l\": %8.2f}", temp, humidity, lux);

For 6 total characters with two digits after the decimal point. I was not sure of how large lux can be, so I bumped it up a bit.

1 Like

@bko I think I may have worked it out actually:

sprintf(json,"{\"t\": %.02f, \"h\": %.02f, \"l\": %.02f}", temp, humidity, lux);

Seems to do the trick at limiting each variable to two decimal places.

2 Likes

Thanks! that is exactly what I needed… we posted at the same time and your answer is 100x better :smile:

2 Likes