Greetings Arduino community,
I am currently facing a challenge involving the serialization of HTML code within a JSON object in Arduino (C++), particularly when using webSockets. The objective is to send HTML content to a client (web browser) through webSockets, with the browser parsing the JSON and inserting the HTML into the specified element identified by the "selector."
Below is the problematic code snippet:
const char netHtml[] = R"(<tr> <td><button id="WIFI_NAME">Connect</button> </div> </td></tr>)"; // Short version
void replaceId(char* html, const char* oldId, const char* newId) {
char* index = NULL;
size_t oldIdLen = strlen(oldId);
while ((index = strstr(html, oldId)) != NULL) {
char tempBuffer[1000]; // Adjust the size as needed
strncpy(tempBuffer, html, index - html);
tempBuffer[index - html] = '\0'; // Null-terminate the temporary buffer
strcat(tempBuffer, newId);
strcat(tempBuffer, index + oldIdLen);
strcpy(html, tempBuffer);
}
}
void publishWifiInfo(boolean append, String ssid, int32_t channel, int32_t rssi, String selector, String request, uint8_t num) {
char newHtml[sizeof(netHtml)];
strcpy_P(newHtml, netHtml);
replaceId((char*)newHtml, "WIFI_NAME", ssid.c_str());
JsonDocument jsonObj;
jsonObj["selector"] = selector;
jsonObj["request"] = request;
jsonObj["append"] = append;
jsonObj["html"] = newHtml;
String jsonString;
serializeJson(jsonObj, jsonString);
webSocket.sendTXT(num, (uint8_t*)jsonString.c_str());
}
The issue arises somewhere, but I really don't know where. The escape sequences are then added before each character, such as ", \ , etc., rendering the HTML code unusable.
I appreciate any insights or suggestions on how to address this problem and prevent the addition of escape sequences, ensuring the proper functionality of the HTML code in the web browser.
The original version was much simpler, and this one may be a bit disorganized due to numerous tests.
Thanks!!
2 posts - 1 participant