迭代json会产生错误

时间:2014-11-01 15:06:34

标签: javascript jquery json

使用此代码访问json数组的元素:

var json = "{\"noteDetailList\": [ {\"linkName\": \"test1\"}]}"

 $.each(json, function() {
                        console.log(data)
                    }); 

to iterate会出现此错误:

Uncaught TypeError: Cannot use 'in' operator to search for '43' in {"noteDetailList": [ {"linkName": "test1"}]} jquery-1.11.0.js:592isArraylike jquery-1.11.0.js:592jQuery.extend.each jquery-1.11.0.js:359(anonymous function) (index):24jQuery.event.dispatch jquery-1.11.0.js:4624elemData.handle jquery-1.11.0.js:4292
小提琴:

http://jsfiddle.net/rsv0tn5e/1/

我没有正确迭代吗?

2 个答案:

答案 0 :(得分:2)

你试图迭代一个字符串!将JSON解析为对象或使用和实际对象:



var jsonString = "{\"noteDetailList\": [ {\"linkName\": \"test1\"}]}";
var json = JSON.parse(jsonString);

// OR

var jsonObj = {
  noteDetailList: [
    {linkName: "test1"}
  ]
};

iterateOverResult(json);
iterateOverResult(jsonObj);

function iterateOverResult(json) {
  $.each(json, function(data) {
    alert(data.toString());
  });
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你必须解析它:

JSON.parse(json);

立即尝试:

var json = "{\"noteDetailList\": [ {\"linkName\": \"test1\"}]}";

$.each(JSON.parse(json), function(data) {
    console.log(data);
});