3

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>

2 Answers 2

6

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

You don't need to parse it.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I thought that JavaScriptSerializer.Serialize() returns a string and not an object literal. I tested just now, I could use a for-in loop to access the key and value, and also access a specify value using jsonString[keyName]
2

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.

1 Comment

Thanks Mattias for the explanation. Accepted SLaks' answer because it was first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.