Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 769
escist Avatar asked Jun 06 '26 19:06

escist


2 Answers

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

You don't need to parse it.

like image 103
SLaks Avatar answered Jun 09 '26 09:06

SLaks


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.

like image 39
Mattias Buelens Avatar answered Jun 09 '26 07:06

Mattias Buelens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!