Ray
Ray

Reputation: 12441

A c# JavaScriptSerializer serialized string has backslashs that cause problems in javascript

I have line of c# code in ASP.NET MVC view that

string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model);

If I debug this string is

"{\"Age\":14}"

So when I assign this string to my javascript code, it fails

JSON.parse('@json');

The message is

Uncaught SyntaxError: Unexpected token &

How do I get around this?

Upvotes: 0

Views: 1940

Answers (2)

Nadir Muzaffar
Nadir Muzaffar

Reputation: 4842

Looks like you're using MVC3, atleast, so try using:

JSON.parse( @Html.Raw(json) );

That spits out a HtmlString type, so instead System.String, you could make the type for json into an HtmlString. Also, you might want to look into the JSON.NET library which is just better (also the default in MVC4, I believe).

Upvotes: 4

Guffa
Guffa

Reputation: 700680

It's not the backslashes that causes the problem, it's the HTML encoding. Actually there isn't any backslashes at all in the string, that's only how the debugger displays a string with quotation marks in it.

The @ command will HTML encode the string, so the code will look like this:

JSON.parse('{"Age":14}');

Use the Raw method to output the string without HTML encoding:

JSON.parse('@Raw(json)');

Upvotes: 2

Related Questions