遍历json对象 [英] loop through a json object

查看:85
本文介绍了遍历json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a json object: slider_data which has value like this:

[{
  "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); 
 });

这非常简单,应该可以使用.但我收到以下错误:

This is pretty simple and should work. But I am getting the following error:

未捕获的TypeError:无法使用'in'运算符在[{"id":"1","image":"http://localdrone2.com/wp-content/uploads/2018/中搜索'length' 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,"标题:" bbbb," more_info:" bbbbb," button_link:" bbbbb"}]

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [{"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"}]

我在做什么错了?

推荐答案

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

The in operator only works on objects. You are using it on a string. Make sure your value is an object before you using $.each. In this specific case, you have to parse the JSON:

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

这篇关于遍历json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆