0

I read a record from my sql server database into a datatable. From there I use newtonsoft's JSON for .NET and run it through

JsonConvert.SerializeObject(DataTable)

I get the following json string output:

[{"Type":"Support-D325","condition":"#2 support beam 1/2\" crack","Length":245.0,"Date_Found":"2018-08-09T08:01:51"}]

and store it in a session variable. Later, client-side I use

data = $.parseJSON('<%= Session("JSONDataTable") %>');

but get the INVALID CHARACTER error. Now I'm guessing its the #2 support beam 1/2\" crack that's doing causing the problem. Is there some JSON command that can fix this so I don't throw the error?

Thank you

Carlos Mendieta
  • 860
  • 16
  • 41
  • 2
    The json string looks properly formatted. The first question I have is what does `'<%= Session("JSONDataTable") %>'` generate to in the actual script? – Taplar Sep 28 '18 at 15:56
  • 1
    See [Is there a standard way to encode a .NET string into JavaScript string for use in MS Ajax?](https://stackoverflow.com/q/2920752); namely, use [`HttpUtility.JavaScriptStringEncode`](https://learn.microsoft.com/en-us/dotnet/api/system.web.httputility.javascriptstringencode?redirectedfrom=MSDN&view=netframework-4.7.2#System_Web_HttpUtility_JavaScriptStringEncode_System_String_) – Heretic Monkey Sep 28 '18 at 15:58
  • 4
    Also, if `Session("JSONDataTable")` is the json string you pasted before, you should be able to do something as simple as `data = <%= Session("JSONDataTable") %>` without having to try to force it to be a string to be parsed. – Taplar Sep 28 '18 at 15:58
  • 1
    Please post the exact error you are receiving; it should tell you what the invalid character is. – Heretic Monkey Sep 28 '18 at 16:11

2 Answers2

1

Your problem is in the "\" character, I recommend that you do the transform to string and replace it, then show it again:

data = $.parseJSON('<%= Session("JSONDataTable") %>');
Hugo Roca
  • 11
  • 1
1

You don't need JSON.parse I believe. Just do it like this:

data = <%= Session("JSONDataTable") %>;
Mohsin Mehmood
  • 4,156
  • 2
  • 12
  • 18