Fixed JSON output for non-ASCII filenames

When exporting to JSON, the "soundFile" string wasn't correctly encoded if it contained non-ASCII characters.
In this case, the resulting JSON was invalid and couldn't be parsed.
This commit is contained in:
Daniel Wolf 2017-08-15 21:05:18 +02:00
parent 5f451feb00
commit 1fb2eb9024
1 changed files with 14 additions and 5 deletions

View File

@ -1,11 +1,17 @@
#include "JsonExporter.h" #include "JsonExporter.h"
#include "exporterTools.h" #include "exporterTools.h"
#include <utf8.h>
using std::string; using std::string;
string escapeJsonString(const string& s) { 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; string result;
for (char c : s) { for (char16_t c : utf16String) {
switch (c) { switch (c) {
case '"': result += "\\\""; break; case '"': result += "\\\""; break;
case '\\': result += "\\\\"; break; case '\\': result += "\\\\"; break;
@ -15,10 +21,13 @@ string escapeJsonString(const string& s) {
case '\r': result += "\\r"; break; case '\r': result += "\\r"; break;
case '\t': result += "\\t"; break; case '\t': result += "\\t"; break;
default: default:
if (c <= '\x1f') { {
bool needsEscaping = c < '\x20' || c >= 0x80;
if (needsEscaping) {
result += fmt::format("\\u{0:04x}", c); result += fmt::format("\\u{0:04x}", c);
} else { } else {
result += c; result += static_cast<char>(c);
}
} }
} }
} }