Skip to content

Instantly share code, notes, and snippets.

@mmalinin
Created November 14, 2013 19:03
Show Gist options
  • Save mmalinin/7472445 to your computer and use it in GitHub Desktop.
Save mmalinin/7472445 to your computer and use it in GitHub Desktop.
/*static*/ String CJSONEntry::quoteValue(const String& strValue)
{
int pos = 0, start_offset = 0;
unsigned char c;
String strRes = "\"";
const char* str = strValue.c_str();
do
{
c = str[pos];
switch(c) {
case '\0':
break;
case '\b':
case '\n':
case '\r':
case '\t':
case '"':
case '\\':
case '/':
if(pos - start_offset > 0)
strRes.append(str + start_offset, pos - start_offset);
if(c == '\b') strRes.append( "\\b", 2 );
else if(c == '\n') strRes.append( "\\n", 2);
else if(c == '\r') strRes.append( "\\r", 2);
else if(c == '\t') strRes.append( "\\t", 2);
else if(c == '"') strRes.append( "\\\"", 2);
else if(c == '\\') strRes.append( "\\\\", 2);
else if(c == '/') strRes.append( "\\/", 2);
start_offset = ++pos;
break;
default:
if(c < ' ')
{
if(pos - start_offset > 0)
strRes.append( str + start_offset, pos - start_offset);
char buf[128];
int nSize = snprintf(buf, 128, "\\u00%c%c", json_hex_chars[c >> 4], json_hex_chars[c & 0xf]);
strRes.append(buf, nSize);
start_offset = ++pos;
}else
pos++;
}
} while(c);
if ( strRes.length() == 1 )
return "\"" + strValue + "\"";
if ( pos - start_offset > 0 )
strRes.append( str + start_offset, pos - start_offset);
strRes.append("\"");
return strRes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment