2015-05-31 48 views
-1

如何訪問此JSON文件中的Marie-Antoinette.json對象?我想獲得對象的標題元素,但我似乎無法得到它的輸出。這是我的JavaScript代碼,它輸出的對象,但我似乎無法訪問對象的元素。使用JavaScript解析JSONP文件

$.ajax(
    { 
     type: 'GET', 
     url: 'http://localhost:5984/movies/efadd5913f5cfd254b2861efd4001cb7', 
     //contentType: "application/json; charset=utf-8", 
     dataType: "JSONP", 
     jsonpCallback: 'callback', 
     //async: false, 
     success: function(r) 
     { 
      alert("ok"); 
      $.each(r, function(index, value){ // iterating over each object 
       console.log(index); 
       if(index == "_attachments") 
       { 
        console.log(value); //how do I output the title ("Marie-Antoinette.json") and the other stuff in the object? 
       } 

      }); 
     } 
    }); 

這是文件。我想訪問的元素位於對象的「_attachments」元素中。

{ 
    "_id": "efadd5913f5cfd254b2861efd4001cb7", 
    "_rev": "6-417588bbff9aa74726b11440a86a8532", 
    "_attachments": { 
     "Marie-Antoinette.json": { 
      "content_type": "application/json", 
      "revpos": 2, 
      "digest": "md5-Io/Pxakfp/4R8ntjQKWMDg==", 
      "length": 761, 
      "stub": true 
     } 
    } 
} 

我認爲拋棄我的是它是_attachment部分中的對象。

+0

http://jsfiddle.net/adeneo/ke61kj8j/ – adeneo

回答

0

Marie-Antoinette.json對象位於您的_attachments對象中,但由於它包含.,因此無法使用點符號進行訪問。你將不得不使用類似數組的符號,傳遞的關鍵是,像這樣的字符串:

success: function (response) { 
    console.log(response._attachments['Marie-Antoinette.json']); 
} 

如果您有多個「附件」,你可以訪問它們在一個循環是這樣的:

success: function (response) { 
    $.each(response._attachments, function (i, attachment) { 
     console.log(attachment); 
    }); 
} 
0

你可以使用Object.keys_attachments對象中提取鍵,然後打印:

var title = Object.keys(r._attachments)[0]; 
console.log(title); 

或者,如果你有多個附件:

var titles = Object.keys(r._attachments); 
console.log(titles.join()); 

Object.keys總是返回一個數組。

0
在功能

success: function(r) 
    { 
     for (key in json._attachments) { 
      console.log(key); // gives the names 
      console.log(json._attachments[key]); // gives the content 
     } 
    } 

,這將使你在_attachments東西