将字符串转换为键值对

时间:2015-10-31 07:09:35

标签: javascript jquery asp.net

我想在我的应用程序中构建一些键值对并在jQuery中读取它。请考虑以下示例代码:

$(document).ready(function (e) {
        var Dictionary = $('#HiddenField1').val();

        $.each(Dictionary , function (key, value) {
            alert(key + ': ' + value);               
        });
    });

并在jQuery中阅读:

jQuery.parseJSON

问题是我想将此字符串转换为键值对。我无法使用Invalid character而我获得new

我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

请忽略',否则字符串是有效的JSON:



var s = "{\"96\": \"0\",";
s += "\"97\": \"1\"}";
var Dictionary = JSON.parse(s);
$.each(Dictionary, function(key, value) {
  snippet.log(key + ': ' + value);
});

<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

我认为应该是:

var s = '{\"96\": \"0\",';
s += '\"97\": \"1\"}';
console.log(JSON.parse(s));
  

对象{96:&#34; 0&#34;,97:&#34; 1&#34;}