Vinny
Vinny

Reputation: 309

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

Upvotes: 0

Views: 1131

Answers (3)

phuzi
phuzi

Reputation: 13060

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);
});

Upvotes: 0

Shyju
Shyju

Reputation: 218722

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/

Upvotes: 0

Skyste
Skyste

Reputation: 66

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 :)

Upvotes: 3

Related Questions