Escaping strings in JSON

If a string is put into JSON it should be escaped as described in the RFC: http://www.ietf.org/rfc/rfc4627.txt

This method should do the trick:

String StringUtils::escapeJSON(const String& jsonString)
{
    String temp;
    String escapedString;
    String::CharPointerType jsonToEscape (jsonString.getCharPointer());

    for(;;)
    {
        const juce_wchar c = jsonToEscape.getAndAdvance();

        if(c == 0)
            break;

        switch (c)
        {

            case '\\':
            case '"':
                escapedString << '\\' << c;
                break;

            case '/':
                escapedString << '\\' << c;
                break;

            case '\b':
                escapedString << "\\b";
                break;

            case '\t':
                escapedString << "\\t";
                break;

            case '\n':
                escapedString << "\\n";
                break;

            case '\f':
                escapedString << "\\f";
                break;

            case '\r':
                escapedString << "\\r";
                break;

            default:
                if (c < ' ')
                {
                    temp = "000" + String::toHexString ((int) c);
                    escapedString << "\\u" << temp.substring(temp.length() - 4);
                }
                else
                {
                    escapedString << c;
                }
        }
    }

    return escapedString;
}

Should this be added to the JSON class?

 

PS: The new WYSIWYG editor added a lot of blank lines when pasting the code above. I had to reformat the whole thing to make it look ok.

The JSON class will escape any strings for you if you create it from a var object and use JSON::toString, though I guess that exposing a utility method to do this could be useful to people.

There's already an internal function JSONFormatter::writeString which (presumably) does exactly the same thing.. Or is the code you posted different in some way?

PS: The new WYSIWYG editor added a lot of blank lines when pasting the code above. I had to reformat the whole thing to make it look ok.

yeah, the trick is to paste without formatting (cmd + shift + V). Or use BBCode mode.