如何在javascript中使用jquery直接访问嵌套的JSON值

时间:2017-10-13 09:57:38

标签: jquery html json url fetch

我有这个链接https://www.googleapis.com/books/v1/volumes?q=isbn:0545010225,它返回一个JSON响应,我想只访问获取的响应的缩略图值。我能够访问初始直接值,但我无法访问嵌套值。

我使用var text = Date: ${data.totalItems}<br>

访问了初始值

但是我无法访问嵌套的那些。我知道它有类似的东西

var text = Date: ${data.items.0.volumeInfo.imageLinks.thumbnail}<br>

1 个答案:

答案 0 :(得分:0)

如果json对象中有数组[],则可能需要循环

$.each(data.items,function(i,v){
   console.log(v.volumeInfo.imageLinks.thumbnail);
})

或只根据数组索引获取一个项目

 data.items[0].volumeInfo.imageLinks.thumbnail

var data = {
 "kind": "books#volumes",
 "totalItems": 1,
 "items": [
  {
   "kind": "books#volume",
   "id": "GZAoAQAAIAAJ",
   "etag": "EtO9HfTXEo8",
   "selfLink": "https://www.googleapis.com/books/v1/volumes/GZAoAQAAIAAJ",
   "volumeInfo": {
    "title": "Harry Potter and the Deathly Hallows",
    "authors": [
     "J. K. Rowling"
    ],
    "publisher": "Arthur a Levine",
    "publishedDate": "2007",
    "description": "The magnificent final book in J. K. Rowling's seven-part saga comes to readers July 21, 2007. You'll find out July 21!",
    "industryIdentifiers": [
     {
      "type": "OTHER",
      "identifier": "UCSC:32106019703807"
     }
    ],
    "readingModes": {
     "text": false,
     "image": false
    },
    "pageCount": 759,
    "printType": "BOOK",
    "categories": [
     "Juvenile Fiction"
    ],
    "averageRating": 4.5,
    "ratingsCount": 3472,
    "maturityRating": "NOT_MATURE",
    "allowAnonLogging": false,
    "contentVersion": "1.0.1.0.preview.0",
    "imageLinks": {
     "smallThumbnail": "http://books.google.com/books/content?id=GZAoAQAAIAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api",
     "thumbnail": "http://books.google.com/books/content?id=GZAoAQAAIAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api"
    },
    "language": "en",
    "previewLink": "http://books.google.ro/books?id=GZAoAQAAIAAJ&dq=isbn:0545010225&hl=&cd=1&source=gbs_api",
    "infoLink": "http://books.google.ro/books?id=GZAoAQAAIAAJ&dq=isbn:0545010225&hl=&source=gbs_api",
    "canonicalVolumeLink": "https://books.google.com/books/about/Harry_Potter_and_the_Deathly_Hallows.html?hl=&id=GZAoAQAAIAAJ"
   },
   "saleInfo": {
    "country": "RO",
    "saleability": "NOT_FOR_SALE",
    "isEbook": false
   },
   "accessInfo": {
    "country": "RO",
    "viewability": "NO_PAGES",
    "embeddable": false,
    "publicDomain": false,
    "textToSpeechPermission": "ALLOWED",
    "epub": {
     "isAvailable": false
    },
    "pdf": {
     "isAvailable": false
    },
    "webReaderLink": "http://play.google.com/books/reader?id=GZAoAQAAIAAJ&hl=&printsec=frontcover&source=gbs_api",
    "accessViewStatus": "NONE",
    "quoteSharingAllowed": false
   },
   "searchInfo": {
    "textSnippet": "The magnificent final book in J. K. Rowling&#39;s seven-part saga comes to readers July 21, 2007. You&#39;ll find out July 21!"
   }
  }
 ]
};
console.log(data.items[0].volumeInfo.imageLinks.thumbnail);