escist
escist

Reputation: 773

jQuery.parseJSON fails to parse serialised C# dictionary

I am using this tutorial to serialise a C# dictionary. The C# dictionary gets serialized to a string. The @Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ElementDivIDs)) works like a charm. This is the output I get,:

  var jsonString = {"9":["ele9-tabs-attr9","ele9-tabs-attr48"],"10":["ele10-tabs-attr10"],"11":["ele11-tabs-attr11"],"12":["ele12-tabs-attr12","ele12-tabs-attr49"],"13":["ele13-tabs-attr13"],"14":["ele14-tabs-attr14"]}

I want to convert this into a Javascript associative array. But the call to jquery.parseJSON returns NULL.

var dictionaryOfOtherDivs = jQuery.parseJSON( jsonString );

dictionaryOfOtherDivs is null after this.

Here's my code:

<script type="text/javascript">
$(document).ready(function () {
     var jsonString = @Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ElementDivIDs))
     console.log(jsonString); 
     var dictionaryOfOtherDivs  = jQuery.parseJSON( jsonString ); 
     for(var dictKey in dictionaryOfOtherDivs)
     { 
        console.log("key = " + dictKey + ", value = " + dictionaryOfOtherDivs[dictKey]); 
     }
     //Do some more things
});
</script>

Upvotes: 3

Views: 1191

Answers (2)

Mattias Buelens
Mattias Buelens

Reputation: 20179

jQuery.parseJSON takes a string and outputs an object. However, you decided to inject the JSON itself right into the script, so the JavaScript engine will already have parsed it into an object literal, as if you'd have written that whole thing yourself as regular code.

Simply put, you already have a parsed object literal, you don't need to do any parsing anymore.

Upvotes: 2

SLaks
SLaks

Reputation: 887767

That's not a JSON string; that's an ordinary object literal.

You don't need to parse it.

Upvotes: 6

Related Questions