title: How to reverse geocode serverside with python, json and google maps?
body: <p>I'm trying serverside reverse geocoding that can get me a json response and now I want to get 2 or 3 variables from the json response:</p>
  
  <p>I'd like to parse for instance this data and end with eg.
  <code>administrative_area_level_1 = 'Stockholm'</code></p>
  
  <p><code>jsondata = json.load(urllib2.urlopen('http://maps.googleapis.com/maps/api/geocode/json?latlng=59.3,18.1&amp;sensor=false'))</code></p>
  
  <p>Here is my python code that fetches the json, now I wonder how to parse it to get just the </p>
  
  <ul>
  <li>administrative_area_level_1 long_name (ie state or region name)</li>
  <li>locality long name (ie city name)</li>
  <li>an understanding how to parse my json</li>
  </ul>
  
  <p>I can parse it but it is not always is comes out as administrative_area_1:</p>
  
  <p><code>jsondata["results"][0]["address_components"][5]["long_name"]</code></p>
  
  <p>The line above correctly outputs "New York" for a point in New York but for Stockholm it outputs a postal city ie Johanneshow which is not the administraive_area_1 (region/state). So how guarantee that the function always returns the administrative_area_1, preferably without looping?</p>
  
  <p>I want it to work something like the following with direct access to country, region and city:</p>
  
  <pre><code>logging.info("country:"+str(jsondata["results"][9]["formatted_address"]))
  logging.info("administrative_area_level_1:"+str(jsondata["results"][8]["formatted_address"]))
  logging.info("locality:"+str(jsondata["results"][8]["formatted_address"]))
  </code></pre>
  
  <p>Thanks in advance</p>
  
  <p>Update</p>
  
  <p>It's a good answer here with the results I expected. While waiting for the answer I also tried implement a solution myself that seems to do it:</p>
  
  <pre><code>jsondata = json.load(urllib2.urlopen('http://maps.googleapis.com/maps/api/geocode/json?latlng='+str(ad.geopt.lat)+','+str(ad.geopt.lon)+'&amp;sensor=false'))
  logging.info("geography:"+str(jsondata["results"][1]["formatted_address"]))
  region = None
  city = None
  for result in jsondata["results"]:
    #logging.info("result:"+str(result))
    for component in result["address_components"]:
      logging.info("components:"+str(component))
      logging.info("components type:"+str(component["types"]))
      if 'administrative_area_level_1' in component["types"]:
        #logging.info(unicode('found admin area:%s' % component["long_name"]))
        region = component["long_name"]
      if 'locality' in component["types"]:
        logging.info("found locality:"+str(component["long_name"]))
        city = component["long_name"]
  </code></pre>
  
  <hr>