Skip to content

Instantly share code, notes, and snippets.

@TvdW
Created September 16, 2012 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TvdW/3732203 to your computer and use it in GitHub Desktop.
Save TvdW/3732203 to your computer and use it in GitHub Desktop.
JSON string encoder, from STL string to JSON
static inline std::string jsonEscape(std::string &str)
{
std::string escaped = "\"";
char buf[16];
unsigned int i;
for (i = 0; i < str.size(); i++)
{
if (str[i] == 34) escaped += '\\';
if (str[i] >= 32 && str[i] <= 126) escaped += str[i];
else {
// UTF8
unsigned char nums[] = {0,0,0,(unsigned char)str[i]};
unsigned char charsLeft = str.size() - i;
if ((nums[3] & 0xF8) == 0xF0) {
if (charsLeft < 4) break;
nums[0] = str[i] & 0x0F;
nums[1] = str[i+1] & 0x1F;
nums[2] = str[i+2] & 0x3F;
nums[3] = str[i+3] & 0x7F;
i += 3;
}
else if ((nums[3] & 0xF0) == 0xE0) {
if (charsLeft < 3) break;
nums[1] = str[i] & 0x1F;
nums[2] = str[i+1] & 0x3F;
nums[3] = str[i+2] & 0x7F;
i += 2;
}
else if ((nums[3] & 0xE0) == 0xC0) {
if (charsLeft < 2) break;
nums[2] = str[i] & 0x3F;
nums[3] = str[i+1] & 0x7F;
i += 1;
}
else {
// 1-char or invalid stuff
// Not UTF-8... BROKEN
nums[3] = str[i] & 0x7F;
}
unsigned short cCode = (nums[0] << 15) + (nums[1] << 11) + (nums[2] << 6) + (nums[3]);
sprintf_s(buf, 16, "\\u%.4X", cCode);
escaped += buf;
}
}
escaped += "\"";
return escaped;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment