2017-02-13 96 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... 
      } 
     } 
    } 
}