2017-02-13 94 views
0

我似乎無法弄清楚如何讓這段代碼工作。我試圖訪問這個json片段中的'Name'對象。任何幫助,將不勝感激。訪問JSON數組中的對象時遇到問題

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> 
 
</script> 
 
<script> 
 
$(document).ready(function() { 
 
\t $.getJSON('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22AAPL%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=', function(data) { 
 
    \t $('#demo').text(data[0].Name); 
 
    }); 
 
}); 
 
</script> 
 
</head> 
 
<body> 
 

 
<p id="demo"></p> 
 

 
</body> 
 
</html>

+0

請提供實際的JSON的問題本身就是一個樣本。可能有人可以幫助您,但無法訪問API網址。 –

回答

1

使用此:

$(document).ready(function() { 
    $.getJSON('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22AAPL%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=', function(data) { 
     $('#demo').text(data.query.results.quote.Name); 
    }); 
}); 
+0

謝謝!我看到我需要訪問每個對象,然後才抓住我想要的那個。 – jrseriel

+0

不客氣。你可以看看這個參考:http://www.w3schools.com/js/js_json.asp –

0
{ 
    "query": { 
     "count": 1, 
     "created": "2017-02-13T18:34:48Z", 
     "lang": "es-419", 
     "results": { 
      "quote": { 
       "name": "Blabla" 

所以,你必須data.query.results.quote.name

0

你的API調用不返回數組它會返回一個JSON對象。

嘗試:$('#demo').text(data.query.results.quote.Name);

這裏是正在被退回的樣子的數據結構:

{ 
    "query": { 
     "count": 1, 
     "created": "2017-02-13T18:34:12Z", 
     "lang": "en-us", 
     "results": { 
      "quote": { 
       // other props... 
       "Name": "Apple Inc.", 
       // other props... 
      } 
     } 
    } 
}