Tuesday, July 12, 2016

Escape JSON string

std::string EscapeJson(const char* text)
{
    std::string string;
    
    int length = strlen(text);
    for (int i = 0; i < length; i++)
    {
        switch (text[i])
        {
            case '\\':
                string.append("\\\\");
                break;
            case '"':
                string.append("\\\"");
                break;
            case '/':
                string.append("\\/");
                break;
            case '\b':
                string.append("\\b");
                break;
            case '\f':
                string.append("\\f");
                break;
            case '\n':
                string.append("\\n");
                break;
            case '\r':
                string.append("\\r");
                break;
            case '\t':
                string.append("\\t");
                break;
            default:
                char c = text[i];
                string.append(1, c < 32 ? '?' : c);
                break;
        }
    }

    return string;
}

No comments:

Post a Comment