When I use System.Web.Script.Serialization.Serialize() to serialize some data from a DataTable that happens to contain a quotation mark, I get a JSON string that appears to be valid.
The VB code I'm using to serialize is this:
Public Shared Function DataTableToJSONWithJavaScriptSerializer(table As DataTable) As String
Dim jsSerializer As New JavaScriptSerializer()
Dim parentRow As New List(Of Dictionary(Of String, Object))()
Dim childRow As Dictionary(Of String, Object)
For Each row As DataRow In table.Rows
childRow = New Dictionary(Of String, Object)()
For Each col As DataColumn In table.Columns
childRow.Add(col.ColumnName, row(col))
Next
parentRow.Add(childRow)
Next
Return jsSerializer.Serialize(parentRow)
End Function
Dim str_sql As String = "SELECT TOP 1 create_date, content FROM tbl_dent"
Dim obj_rdr As SqlDataReader
' ...
' some code suppressed for brevity
Dim obj_dt As New DataTable()
obj_dt.Load(obj_rdr)
Dim str_javascript_string As String = "var str = '" _
& DataTableToJSONWithJavaScriptSerializer(obj_dt).Replace("[","").Replace("]","") & "';"
' append this script to web page
EDIT (solution, per @Heinzi's answer below):
'instead of this:
Dim str_javascript_string As String = "var str = '" _
& DataTableToJSONWithJavaScriptSerializer(obj_dt).Replace("[","").Replace("]","") & "';"
'this:
Dim jsSecondSerializer As New JavaScriptSerializer()
Dim str_javascript_string As String = "var str = " _
& jsSecondSerializer.serialize(DataTableToJSONWithJavaScriptSerializer(obj_dt).Replace("[","").Replace("]","")) & ";"
An example of the output (that contains a quotation mark) is this:
var str = '{"create_date":"2017-09-08T22:30:11.674Z","content":"This dent is 4\" wide."}';
But when I try to parse it, like this:
var obj = JSON.parse(str);
I get this error: Uncaught SyntaxError: Unexpected token w in JSON at position 69
Why? I can't imagine that I need to manually search for and double-escape quote-marks...? Surely I can rely on the serializer to properly generate a usable json string?