3

我正在使用本教程来序列化 C# 字典。C# 字典被序列化为字符串。这些@Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ElementDivIDs))作品就像一个魅力。这是我得到的输出:

  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"]}

我想将其转换为 Javascript 关联数组。但是对jquery.parseJSON的调用返回 NULL。

var dictionaryOfOtherDivs = jQuery.parseJSON( jsonString );

dictionaryOfOtherDivs在此之后为空。

这是我的代码:

<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>
4

2 回答 2

6

那不是 JSON 字符串;那是一个普通的对象文字。

你不需要解析它。

于 2012-05-31T13:09:37.973 回答
2

jQuery.parseJSON接受一个字符串并输出一个对象。但是,您决定将 JSON 本身直接注入脚本中,因此 JavaScript 引擎已经将其解析为对象字面量,就好像您自己将整个内容编写为常规代码一样。

简单地说,你已经有了一个解析的对象字面量,你不需要再做任何解析了。

于 2012-05-31T13:11:24.363 回答