简体   繁体   中英

Trouble with accessing object in JSON array

I can't seem to figure out how to get this code snippet to work. I am trying to access the 'Name' object in this json snippet. Any help would be appreciated.

 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> </script> <script> $(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[0].Name); }); }); </script> </head> <body> <p id="demo"></p> </body> </html> 

Use this:

$(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);
    });
});
{
    "query": {
        "count": 1,
        "created": "2017-02-13T18:34:48Z",
        "lang": "es-419",
        "results": {
            "quote": {
              "name": "Blabla"

So you have data.query.results.quote.name

Your API call does not return an array, it returns a JSON object.

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

Here's what the data structure that is being returned looks like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM