在jquery中循环遍历嵌套对象

时间:2014-01-20 08:41:13

标签: json jquery

Iam newbie to jquery。我需要解析一个JSON。我尝试使用$每个语句,但坚持使用[object,object]循环。这是我用于解析JSON的代码。帮助我解决这个问题。

var myjson='[{"isTruncated": "false","nextMarker": "null","marker": "null","prefix":   "Mymedia/mysys/","contents": [{"deviceInfo": "null","lastModified": "Thu Dec 26 16:36:42 IST 2013","etag": "d41d8cd98f00b204e9800998ecf8427e","key":"Mymedia/mysys/audio_$folder$","size": "0"},{"deviceInfo": null,"lastModified": "Thu Dec 26 16:36:11 IST 2013","etag": "d41d8cd98f00b204e9800998ecf8427e","key": "Mymedia/mysys/doc_$folder$","size": "0"},{ "deviceInfo": null,"lastModified": "Thu Dec 26 16:36:20 IST 2013", "etag": "d41d8cd98f00b204e9800998ecf8427e","key": "Mymedia/mysys/imge_$folder$","size": "0"},{"deviceInfo": null,"lastModified": "Thu Dec 26 16:36:56 IST 2013","etag": "d41d8cd98f00b204e9800998ecf8427e","key":"Mymedia/mysys/others_$folder$","size": "0"},{"deviceInfo": null,"lastModified": "Thu Dec 26 16:36:32 IST 2013","etag": "d41d8cd98f00b204e9800998ecf8427e","key": "Mymedia/mysys/video_$folder$","size": "0"}],"name": "name", "statusCode": "200","statusMessage": "Success","error": null}]';

 var dataobj = $.parseJSON(JSON.stringify(myjson));

             $.each(dataobj, function (key, val) {
                 alert(key + val);
                 if (key == "contents") {
                     $.each(val, function (mykey, values) { alert(mykey + values) });
                     $.each(values, function (key, pairs) {alert(pairs) });

                 }

             });

我无法遍历JSON对象(内容)并获取其中的项目。我需要获取内部关键内容对象。指出我出错的地方。

1 个答案:

答案 0 :(得分:1)

使用针对此问题提到的堆栈溢出链接我已经解决了这个问题。我已经发布了以下代码。

 var Listobj = new Array();
 var dataobj = $.parseJSON(JSON.stringify(myjson));

 $.each(dataobj, function (key, val) {
                 alert(key + val);
                 if (key == "contents") {
                     for (var i = 0, l = val.length; i < l; i++) {
                         var obj = val[i];
                         alert(obj.key);
                         Listobj[i] = obj.key;
                     }

                 }

             });