简体   繁体   中英

Parsing JSON data with jQuery

So I'm using Yahoo's API to translate coordinates to a zip code. The JSON it returns is this:

{
"ResultSet": {
    "version": "1.0",
    "Error": 0,
    "ErrorMessage": "No error",
    "Locale": "us_US",
    "Quality": 99,
    "Found": 1,
    "Results": [{
         ....
     }]

What I am doing is:

$.getJSON("http://where.yahooapis.com/geocode?q=" + lat + ",+" + lon + "&gflags=R&flags=J", function(data){
            console.log(data.ResultSet.Results.postal);
        });

What I listed above obviously doesn't work. My question is: how do I access the data within the Results array?

Thanks

as Results is an array does changing the console log line to the following work?

console.log(data.ResultSet.Results[0].postal)

In which case just loop through the array to get each each element. The code to get JSON looks fine to me, I assume you just missed the array element bit :)

This should work.

$.getJSON("http://where.yahooapis.com/geocode?q=234532,234533&gflags=R&flags=J", function(data){
   $.each(data.ResultSet.Results,function(i,item){
      console.log(data.ResultSet.Results[i].postal);
   });     
});

Example : http://jsfiddle.net/ALsHH/11/

The line console.log(data.ResultSet.Results.postal); is attempting to access a property called portal on an object called data.ResultSet.Results however the property doesn't exist as Results is an array of objects.

What you'll probably need to do is iterate of the array something like...

$.getJSON("http://where.yahooapis.com/geocode?q=" + lat + ",+" + lon + "&gflags=R&flags=J", function(data){
    for (var i=0; i< data.ResultSet.Results.length; i++) {
        console.log("data.ResultSet.Results[i].postal = " + data.ResultSet.Results[i].postal);
});

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