Skip to content Skip to sidebar Skip to footer

Jquery 1.9.1 Fails To Parse Json That Contains Escaped Backslash

Question: how can I use the asp.net JavascriptSerializer on the server to create JSON strings that will always work with the jquery 1.9.1 parseJSON() method in IE 9? On the server

Solution 1:

You are drawing the wrong conclusions. You are changing the environment where the data is evaluated and that's why you get seemingly contradicting results.

Lets start with.

{"HasBackslash":"Has\Backslash"}

It's invalid JSON because \B is an invalid escape sequence.

{"HasBackslash":"Has\\Backslash"}

is valid because \\ is a valid escape sequence. When the JSON is parsed, it will create the character \.

Now to:

$.parseJSON('{"HasBackslash":"Has\\Backslash"}');

Since you are working with a JavaScript string where \ is the escape character as well, the \ are considered to be part of the string literal. Just try

> console.log('{"HasBackslash":"Has\\Backslash"}');
{"HasBackslash":"Has\Backslash"}

You see, the string value, which is the real value that is passed to $.parseJSON, is the same as first one, which was invalid.

However,

$.parseJSON('{"HasBackslash":"Has\Backslash"}');

works, since again, you are working with a JavaScript string, so the value being parsed is

> console.log('{"HasBackslash":"Has\Backslash"}');
{"HasBackslash":"HasBackslash"}

which does not contain a backslash.


So, as long as you are not embedding the generated JSON into a JavaScript string, you should be fine.

Solution 2:

Thank you for your patience @Felix Kling. In sum, here is what I was doing wrong. Server-side I was first creating a JSON string from an object:

string jsonString = new JavaScriptSerializer.Serialize(myObject);

then, from the server, injecting this bit of javascript into the page:

"var o = $.parseJSON('" + jsonString + "');";

The problem is the call to $.parseJSON. This is not needed; I already have a ready-made JSON object. All I need to inject is this:

"var o = " + jsonString + ";";

And, if you are doing this in an MVC cshtml page in a block of Javascript, remember to preface with Html.Raw():

varo=@Html.Raw(jsonStringVariable);    

Post a Comment for "Jquery 1.9.1 Fails To Parse Json That Contains Escaped Backslash"