Escape Quote in C# for javascript consumption

后端 未结 9 1187
天涯浪人
天涯浪人 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 18:03
    string.Replace(<mystring>, @"\"", @"\\"");
    
    0 讨论(0)
  • 2020-11-27 18:04

    To correctly escape a string literal for Javascript, you first escape all backslash characters, then you escape the quotation marks (or apostrophes if you use them as string delimiters).

    So, what you need is:

    value.Replace("\\","\\\\").Replace("\"","\\\"")
    

    What else jumps out to me is that you are using string concatenation in a loop. This is bad, as it scales very poorly. The += operator does not add characters at the end of the existing string (as strings are immutable and can never be changed), instead it copies the string and the added characters to a new string. As you copy more and more data each time, eEvery additional row roughly doubles the execution time of the method. Use a StringBuilder to build the string instead.

    Use the ColumnName property to get the name of a column rather than the ToString method. The ToString method returns the Expression property value if it's set, only if that is not set does it return the ColumnName property.

    public static String dt2JSON(DataTable dt) {
       StringBuilder s = new StringBuilder("{\"rows\":[");
       bool firstLine = true;
       foreach (DataRow dr in dt.Rows) {
          if (firstLine) {
             firstLine = false;
          } else {
             s.Append(',');
          }
          s.Append('{');
          for (int i = 0; i < dr.Table.Columns.Count; i++) {
             if (i > 0) {
                s.Append(',');
             }
             string name = dt.Columns[i].ColumnName;
             string value = dr[i].ToString();
             s.Append('"')
                .Append(name.Replace("\\","\\\\").Replace("\"","\\\""))
                .Append("\":\"")
                .Append(value.Replace("\\","\\\\").Replace("\"","\\\""))
                .Append('"');
          }
          s.Append("}");
       }
       s.Append("]}");
       return s.ToString();
    }
    
    0 讨论(0)
  • 2020-11-27 18:05

    For .net 4.0 + there is standard HttpUtility.JavaScriptStringEncode

    For earlier west wind solution described by Lone Coder is quite nice

    0 讨论(0)
提交回复
热议问题