Escape Quote in C# for javascript consumption

后端 未结 9 1186
天涯浪人
天涯浪人 2020-11-27 17:24

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\\\":[\";
         


        
相关标签:
9条回答
  • 2020-11-27 17:49

    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();
    }
    
    0 讨论(0)
  • 2020-11-27 17:52

    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! :)

    0 讨论(0)
  • 2020-11-27 17:53

    Works when i need send string from C# to html tag.

    <buton onlick="alert('<< here >>')" />
    
    HttpUtility.HtmlEncode
    
    0 讨论(0)
  • 2020-11-27 17:54

    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:

    • Remove double quoting wrapping since I do it in the js
    • Use expression body
    • Use a cleaner switch
    • Use Linq
    • Add a check for Letter to allow é
    0 讨论(0)
  • 2020-11-27 17:54

    Why don't you just do this:

    string correctResponseText = wrongResponseText.Replace("\"", "\\\"");
    
    0 讨论(0)
  • 2020-11-27 18:02

    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("\",""))
    
    0 讨论(0)
提交回复
热议问题