Skip to content

Commit

Permalink
Ensure json is formatted correctly (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
DTTerastar authored Jan 21, 2024
1 parent 84c8d24 commit 27c2d2d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 9 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ node_modules
cmake-build-*
CMakeLists.txt
CMakeListsPrivate.txt
.DS_Store
41 changes: 32 additions & 9 deletions src/AsyncWiFiSettings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,29 @@ namespace { // Helpers
return r;
}

String json_encode(const String &raw) {
String r;
for (unsigned int i = 0; i < raw.length(); i++) {
char c = raw.charAt(i);
switch (c) {
case '\"': r += "\\\""; break;
case '\\': r += "\\\\"; break;
case '\b': r += "\\b"; break;
case '\f': r += "\\f"; break;
case '\n': r += "\\n"; break;
case '\r': r += "\\r"; break;
case '\t': r += "\\t"; break;
default:
if (c < ' ' || c > '~') {
r += Sprintf("\\u%04x", c);
} else {
r += c;
}
}
}
return r;
}

struct AsyncWiFiSettingsParameter {
String name;
String label;
Expand Down Expand Up @@ -102,8 +125,8 @@ namespace { // Helpers
String json() {
if (value == "") return "";
String j = F("\"{name}\":\"{value}\"");
j.replace("{name}", name);
j.replace("{value}", value);
j.replace("{name}", json_encode(name));
j.replace("{value}", json_encode(value));
return j;
}

Expand Down Expand Up @@ -147,8 +170,8 @@ namespace { // Helpers
String json() {
if (value == "") return "";
String j = F("\"{name}\":\"{value}\"");
j.replace("{name}", name);
j.replace("{value}", value);
j.replace("{name}", json_encode(name));
j.replace("{value}", json_encode(value));
return j;
}

Expand Down Expand Up @@ -189,8 +212,8 @@ namespace { // Helpers
String json() {
if (value == "") return "";
String j = F("\"{name}\":\"{value}\"");
j.replace("{name}", name);
j.replace("{value}", value);
j.replace("{name}", json_encode(name));
j.replace("{value}", String(value.toInt()));
return j;
}

Expand All @@ -213,8 +236,8 @@ namespace { // Helpers
String json() {
if (value == "") return "";
String j = F("\"{name}\":{value}");
j.replace("{name}", name);
j.replace("{value}", value);
j.replace("{name}", json_encode(name));
j.replace("{value}", String(value.toFloat()));
return j;
}

Expand All @@ -237,7 +260,7 @@ namespace { // Helpers
String json() {
if (value == "") return "";
String j = F("\"{name}\":{value}");
j.replace("{name}", name);
j.replace("{name}", json_encode(name));
j.replace("{value}", value.toInt() ? "true" : "false");
return j;
}
Expand Down

0 comments on commit 27c2d2d

Please sign in to comment.