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>
That's not a JSON string; that's an ordinary object literal.
You don't need to parse it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With