I have a ASP.Net web handler that returns results of a query in JSON format
public static String dt2JSON(DataTable dt)
{
String s = \"{\\\"rows\\\":[\";
Here is an efficient and robust method that I found at http://www.west-wind.com/weblog/posts/114530.aspx
/// <summary>
/// Encodes a string to be represented as a string literal. The format
/// is essentially a JSON string.
///
/// The string returned includes outer quotes
/// Example Output: "Hello \"Rick\"!\r\nRock on"
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string EncodeJsString(string s)
{
StringBuilder sb = new StringBuilder();
sb.Append("\"");
foreach (char c in s)
{
switch (c)
{
case '\"':
sb.Append("\\\"");
break;
case '\\':
sb.Append("\\\\");
break;
case '\b':
sb.Append("\\b");
break;
case '\f':
sb.Append("\\f");
break;
case '\n':
sb.Append("\\n");
break;
case '\r':
sb.Append("\\r");
break;
case '\t':
sb.Append("\\t");
break;
default:
int i = (int)c;
if (i < 32 || i > 127)
{
sb.AppendFormat("\\u{0:X04}", i);
}
else
{
sb.Append(c);
}
break;
}
}
sb.Append("\"");
return sb.ToString();
}
I think you should rather look at the JavaScriptSerializer class. It's a lot more stable, and will correctly handle any kind of data or escape characters etc. Also, your code will look a lot cleaner.
In your case your class can look like this:
public static String dt2JSON(DataTable dt) {
var rows = new List<Object>();
foreach(DataRow row in dt.Rows)
{
var rowData = new Dictionary<string, object>();
foreach(DataColumn col in dt.Columns)
rowData[col.ColumnName] = row[col];
rows.Add(rowData);
}
var js = new JavaScriptSerializer();
return js.Serialize(new { rows = rows });
}
This method will return a correctly serialized json string... For example, sth like this:
{"rows":[{"id":1,"name":"hello"},{"id":2,"name":"bye"}]}
Have fun! :)
Works when i need send string from C# to html tag.
<buton onlick="alert('<< here >>')" />
HttpUtility.HtmlEncode
Here is a rework of @Bryan Legend's answer with Linq:
public static string EncodeJavaScriptString(string s)
=> string.Concat(s.Select(c => {
switch (c)
{
case '\"': return "\\\"";
case '\\': return "\\\\";
case '\b': return "\\b";
case '\f': return "\\f";
case '\n': return "\\n";
case '\r': return "\\r";
case '\t': return "\\t";
default: return (c < 32 || c > 127) && !char.IsLetterOrDigit(c) ? $"\\u{(int)c:X04}" : c.ToString();
}}));
Try it Online!
changelog:
é
Why don't you just do this:
string correctResponseText = wrongResponseText.Replace("\"", "\\\"");
Well, for starters you do not need quotes around the keys.
{rows:[,]} is valid.
and you could dt.Table.Columns[i].ToString().Replace("\","")
But if you want to retain the double quotes, single quote works the same way double quotes do in JS
Otherwise you could do
String.Format("{name: \"{0}\"}",Columns[i].ToString().Replace("\",""))