I have a project where I need to send a JSON string in an MQTT message.
Using the ArduinoJson library makes generating the JSON string fairly easy, but to send the JSON string as an MQTT message, I have to escape the quotes.
{"temperature":"65.43"} has to be sent as: {"temperature":"65.43"}
I couldn't find a function or method to escape the quotes in the string, so I wrote one.
// Demo of a function to escape quotes in a c-string.
char fooBufer[150]; //Holds the results of escapeQuotes()
// ======= setup() =======
void setup(void)
{
Serial.begin(115200);
delay(10);
Serial.println();
Serial.println();
char foo[] = R"(He said: "The Quick Brown Fox".)";
Serial.print(F("foo= "));
Serial.println(foo);
escapeQuotes(foo);
Serial.print(F("fooBufer = "));
Serial.println(fooBufer);
}
// ======= loop() =======
void loop(void) {
}
// ======= escapeQuotes() =======
void escapeQuotes(char *foos) {
//Function to take a c-string containing quotes and fill a c-string with the quotes escaped.
//For example:
// (He said "The Quick Brown Fox".)
//becomes:
// (He said \"The Quick Brown Fox\".)
//
char *p = foos;
int j = 0;
for (int i = 0; i < strlen(p); i++) {
if (p[i] == 34) {
fooBufer[j++] = 92; // Backslash character
fooBufer[j++] = 34; // Quote character
} else {
fooBufer[j++] = p[i]; // Not a quote, keep it.
}
}
}
Do you see any problems with the function escapeQuotes() , or is there a better way?
Q2: I am still learning to use c-strings wherever possible, but I still haven't figured out how to return a c-string from a function. Tips here would be appreciated.