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 I am calling JavascriptSerializer.Serialize() on an object to convert it to a JSON string. The object has properties which can contain a backslash. So the JavascriptSerializer takes a value like this:

Has\Backslash

And escapes it like this:

Has\\Backslash

When I run the resulting JSON string through JsonLint it is validated:

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

And when I run this through JsonLint it throws a parse error:

{"HasBackslash":"Has\Backslash"}

In IE9/jquery 1.9.1 the exact opposite is acceptable. The bit of Javascript created by JavascriptSerializer on the server fails in the browser with the error "Invalid Character":

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

But this bit of Javascript works just fine:

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

Here is full example, I'm using jquery 1.9.1 and IE 9.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>The Title</title>
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        try {
            var NoBackslash = $.parseJSON('{"NoBackslash":"No Backslash"}');
            $('#NoBackslash').text('NoBackslash parsed successfully');
        }
        catch(err){
            $('#NoBackslash').text('Error parsing NoBackslash: ' + err.message);
        }

        try {
            var HasBackslash = $.parseJSON('{"HasBackslash":"Has\Backslash"}');
            $('#HasBackslash').text('HasBackslash parsed successfully');
        }
        catch (err) {
            $('#HasBackslash').text('Error parsing HasBackslash: ' + err.message);
        }


        try {
            var HasEscapedBackslash = $.parseJSON('{"HasEscapedBackslash":"Has\\Backslash"}');
            $('#HasEscapedBackslash').text('HasEscapedBackslash parsed successfully');
        }
        catch(err){
            $('#HasEscapedBackslash').text('Error parsing HasEscapedBackslash: ' + err.message);
        }

    });
</script>
</head>
<body>
    <p id='NoBackslash'></p>
    <p id='HasBackslash'></p>
    <p id='HasEscapedBackslash'></p>
</body></html>

Related posts

Recent Viewed