jQuery多阵列JSON警报?

时间:2013-09-28 14:38:57

标签: javascript jquery json

我整晚都在尝试这个,但似乎无法获得

{"files": [
  {
    "name": "picture1.jpg",
    "size": 902604,
    "url": "http:\/\/example.org\/files\/picture1.jpg",
    "thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture1.jpg",
    "deleteUrl": "http:\/\/example.org\/files\/picture1.jpg",
    "deleteType": "DELETE"
  },
  {
    "name": "picture2.jpg",
    "size": 841946,
    "url": "http:\/\/example.org\/files\/picture2.jpg",
    "thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture2.jpg",
    "deleteUrl": "http:\/\/example.org\/files\/picture2.jpg",
    "deleteType": "DELETE"
  }
]}

我一直试图获取每个文件的名称......所以我所做的就是这个。

var obj = JSON.parse(data.result);
        for(var i in obj.files){
        var urlstring;
        urlstring = obj.files[i].name;
        alert(urlstring);
        }

但不知怎的,它不允许我提醒每个人的名字......我知道我该如何去做呢?

1 个答案:

答案 0 :(得分:1)

假设,

var data  = {"files": [
  {
    "name": "picture1.jpg",
    "size": 902604,
    "url": "http:\/\/example.org\/files\/picture1.jpg",
    "thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture1.jpg",
    "deleteUrl": "http:\/\/example.org\/files\/picture1.jpg",
    "deleteType": "DELETE"
  },
  {
    "name": "picture2.jpg",
    "size": 841946,
    "url": "http:\/\/example.org\/files\/picture2.jpg",
    "thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture2.jpg",
    "deleteUrl": "http:\/\/example.org\/files\/picture2.jpg",
    "deleteType": "DELETE"
  }
]};

尝试,

$.each(data, function(i, items) {
    $.each(items, function(j, item) {
       alert(item.name);
    });
});

<强> Working fiddle Here


修改

您的数据格式错误,因此您需要正确格式化。

请查看以下数据和工作小提琴。

var data  = '{"files": ['+
'{"name": "picture1.jpg","size": 902604,"url":"http:\/\/example.org\/files\/picture1.jpg","thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture1.jpg","deleteUrl": "http:\/\/example.org\/files\/picture1.jpg","deleteType": "DELETE"},' +
'{"name":"picture2.jpg","size":841946,"url":"http:\/\/example.org\/files\/picture2.jpg","thumbnailUrl":"http:\/\/example.org\/files\/thumbnail\/picture2.jpg","deleteUrl":"http:\/\/example.org\/files\/picture2.jpg","deleteType":"DELETE"}]}';

var obj = JSON.parse(data);

for(var i in obj.files){
        var urlstring;
        urlstring = obj.files[i].name;
        alert(urlstring);
}

Working fiddle with your code