Hey, so I have been trying to get some json data off my photon, and found that lots of people have issues when it comes to using sprintf.
Help with “sprintf” formatting for doubles in preparation for JSON
Issues with converting float to string with sprintf
[Solved] Problem using sprintf on spark
The topics above were all great and helpful, but no real solution exists if you’re trying to return data as such on a photon:
{"Humidity":49.10, "Celsius":23.60, "Feels Like":25.25}
Why? Because all you get on the other side when you do:
sprintf(publishString,"{\"Humidity\": %2.2f, \"Celsius\": %2.2f, \"Feels Like\": %2.2f}",h,t,hi);
or
sprintf(publishString,"{\"Humidity\": %f, \"Celsius\": %f, \"Feels Like\": %f}",h,t,hi);
is the following:
{"Humidity":49.10, "Celsius":23.60, "Feels Like":25.25}
This is true as of SPARK FIRMWARE V0.3.4 (OCT 21). So likely this post will be deleted at some point when this is fixed.
Luckily, this is C++, and even though I am not an avid C++ developer, I was able to figure this out, so here goes how I solved this issue myself.
// make sure this is outside your loop
char publishString[64];
// And then inside your loop
strcpy (publishString,"{\"Humidity\":");
strcat (publishString,String(h, 2));
strcat (publishString,", \"Celsius\":");
strcat (publishString,String(t, 2));
strcat (publishString,", \"Feels Like\":");
strcat (publishString,String(hi, 2));
strcat (publishString,"}");
This is just string concatenation (instead of interpolation), but works a treat. References for strcat and strcpy are linked.
Let me know if you know of any different solutions