JayB127
JayB127

Reputation: 83

Is it possible to search JSON data for a specific key?

I'm using Google Maps Geocoding API in conjunction with Google Places Autocomplete API for iOS to search for addresses and return a zip code. When the JSON Data is returned, I store it in an NS Dictionary and then use a conditional to check the number of components returned. In my first test address, the zipcode is returned at index 8 within the address_components, so I was using the following conditional:

if ([[[[json objectForKey: @"results"]objectAtIndex:0] objectForKey:@"address_components"] count]>=8) {
//stuff
}

On my second test address, however, the zipcode is at index 7. Instead of trying to modify my conditional to account for every possible way that the json data could be returned, is it possible for me to search the json data for a zip-code specifically before returning anything? The json data for the zipcode (within the address components key) looks like this:

{
"long_name" = 20001;
"short_name" = 20001;
 types =   (
"postal_code"
     );

Is there a way for me to search for the "postal_code" type and return the "long_name" for it? Alternatively, is it possible to write a Geocoding API call that returns ONLY the zipcode if it exists?

Upvotes: 0

Views: 255

Answers (2)

kabarga
kabarga

Reputation: 803

I guess you have to parse json with e.g.

NSDictionary *parsedDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&parseError];

and then check the dictionary. because what if you will have 2,3 @"results"?

based on the Google Maps Geocoding API:

Generally, only one entry in the "results" array is returned for address lookups,though the geocoder may return several results when address queries are ambiguous.

Note that these results generally need to be parsed if you wish to extract values from the results.

Upvotes: 0

Ian MacDonald
Ian MacDonald

Reputation: 14030

Here's your postal codes:

for (NSDictionary *component in json[@"results"][0][@"address_component"]) {
  if ([component[@"types"] containsObject:@"postal_code"]) {
    return component[@"long_name"];
  }
}

Upvotes: 1

Related Questions