2015-05-31 49 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东西