diff --git a/src/exporters/JsonExporter.cpp b/src/exporters/JsonExporter.cpp index be76a3b..b228d31 100644 --- a/src/exporters/JsonExporter.cpp +++ b/src/exporters/JsonExporter.cpp @@ -1,11 +1,17 @@ #include "JsonExporter.h" #include "exporterTools.h" +#include using std::string; string escapeJsonString(const string& s) { + // JavaScript uses UTF-16 internally. As a result, character escaping in JSON strings is UTF-16-based. + // Convert string to UTF-16 + std::u16string utf16String; + utf8::utf8to16(s.begin(), s.end(), std::back_inserter(utf16String)); + string result; - for (char c : s) { + for (char16_t c : utf16String) { switch (c) { case '"': result += "\\\""; break; case '\\': result += "\\\\"; break; @@ -15,10 +21,13 @@ string escapeJsonString(const string& s) { case '\r': result += "\\r"; break; case '\t': result += "\\t"; break; default: - if (c <= '\x1f') { - result += fmt::format("\\u{0:04x}", c); - } else { - result += c; + { + bool needsEscaping = c < '\x20' || c >= 0x80; + if (needsEscaping) { + result += fmt::format("\\u{0:04x}", c); + } else { + result += static_cast(c); + } } } }