HTML Code Serialization Issue in Arduino (C++) with WebSockets and JSON

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!!

assuming you use ArduinoJSON, try to change

into

  jsonObj["html"] = serialized(newHtml); // see https://arduinojson.org/v6/api/misc/serialized/

Description

serialized() allows you to insert preformatted chunks of JSON (or MessagePack) in a JsonObject or a JsonArray.

Unlike with regular string value, ArduinoJson doesn’t escape the special characters when the string is marked as “serialized.”

You can use this function when you have a part of the document that never changes; you can hard-code this part in the source code, to optimize the serialization.

You can also use this function to insert a part that you cannot recreate with the library.

Thanks!!! It worked!

Have fun :wink:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.