[英]Convert string to Key Value Pair
我想在我的应用程序中构建一些键值对并在jQuery中读取它。请考虑以下示例代码:
string s = "'{\"96\": \"0\",";
s += "\"97\": \"1\"}'";
HiddenField1.Value = s;
并在jQuery中阅读:
$(document).ready(function (e) {
var Dictionary = $('#HiddenField1').val();
$.each(Dictionary , function (key, value) {
alert(key + ': ' + value);
});
});
问题是我想将此字符串转换为键值对。 我无法使用jQuery.parseJSON
并且得到了Invalid character
。
我该怎么做?
只需省略'
,否则字符串是有效的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>
我认为应该是:
var s = '{\"96\": \"0\",';
s += '\"97\": \"1\"}';
console.log(JSON.parse(s));
对象{96:“ 0”,97:“ 1”}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.