Server side safe JSON

We are working on a project which involves a lot of JQuery and JSON. We wanted to make sure that the JSON does not fail to evaluate so I got the function given below (after a bit of searching) to make the string safe so that it successfully evaluates. There you go…..

// Make a string safe for JSON evaluation
private static string SafeJSON(string sIn)
{
    StringBuilder sbOut = new StringBuilder(sIn.Length); //using the StringBuilder Class for performance
    foreach (char ch in sIn) //Looping through the string (dont u think a counter is better???)
    {
        if (Char.IsControl(ch) || ch == '\'')
        {
            int ich = (int)ch;
            sbOut.Append(@"\u" + ich.ToString("x4"));
            continue;
        }
        else if (ch == '\"' || ch == '\\' || ch == '/')
        {
            sbOut.Append('\\');
        }
        sbOut.Append(ch);
    }
    return sbOut.ToString();
}

Hope this helps.

Happy Programming!!!

Cheers,

Raja

Advertisements

0 Responses to “Server side safe JSON”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s





%d bloggers like this: