循环遍历json对象

时间:2018-02-14 11:13:02

标签: jquery json

我有一个json对象:slider_data,其值如下:

[{
  "id": "1",
  "image": "http:\/\/localdrone2.com\/wp-content\/uploads\/2018\/02\/slider-1-1.jpg",
  "title": "aaa",
  "more_info": "aaaaa",
  "button_link": "aaaaa"
}, 
{
  "id": "2",
  "image": "http:\/\/localdrone2.com\/wp-content\/uploads\/2018\/02\/slider-3-6.jpg",
  "title": "bbbb",
  "more_info": "bbbbb",
  "button_link": "bbbbb"
}]

我只想按如下方式遍历这些数据:

 $.each(slider_data, function(index, element) {
        console.log(element); 
 });

这很简单,应该可行。但我收到以下错误:

  

未捕获的TypeError:无法在'中使用'运营商搜索'长度'在[{" id":" 1"," image":" http://localdrone2.com/wp-content/uploads/2018/ 02 /滑块1-1.jpg""标题":" AAA"" MORE_INFO":" AAAAA",& #34; button_link":" AAAAA"},{" ID":" 2""图像":" http://localdrone2.com/wp-content/uploads/2018/02/slider-3-6.jpg","title":"bbbb"," ; more_info":" bbbbb"," button_link":" bbbbb"}]

我做错了什么?

2 个答案:

答案 0 :(得分:2)

in运算符仅适用于对象。您正在使用字符串。在使用$ .each之前,请确保您的值是一个对象。在这种特定情况下,您必须解析JSON:

$.each(JSON.parse(myData), ...);

答案 1 :(得分:0)

是。在循环之前解析解决了问题:

var json_data = absbBtToS.slider_data;
    var slider_data = JSON.parse(json_data);

        console.log(slider_data); 
    $.each(slider_data, function(index, element) {

        console.log(element); 
    });