0

Hello I am completely new to flask and python. I am using an API to geocode and i get a json which is

"info": {
    "copyright": {
      "imageAltText": "\u00a9 2015 MapQuest, Inc.", 
      "imageUrl": "http://api.mqcdn.com/res/mqlogo.gif", 
      "text": "\u00a9 2015 MapQuest, Inc."
    }, 
    "messages": [], 
    "statuscode": 0
  }, 
  "options": {
    "ignoreLatLngInput": false, 
    "maxResults": -1, 
    "thumbMaps": true
  }, 
  "results": [
    {
      "locations": [
        {
          "adminArea1": "US", 
          "adminArea1Type": "Country", 
          "adminArea3": "", 
          "adminArea3Type": "", 
          "adminArea4": "", 
          "adminArea4Type": "County", 
          "adminArea5": "", 
          "adminArea5Type": "City", 
          "adminArea6": "", 
          "adminArea6Type": "Neighborhood", 
          "displayLatLng": {
            "lat": 33.663512, 
            "lng": -111.958849
          }, 
          "dragPoint": false, 
          "geocodeQuality": "ADDRESS", 
          "geocodeQualityCode": "L1AAA", 
          "latLng": {
            "lat": 33.663512, 
            "lng": -111.958849
          }, 
          "linkId": "25438895i35930428r65831359", 
          "mapUrl": "http://www.mapquestapi.com/staticmap/v4/getmap?key=&rand=1009123942", 
          "postalCode": "", 
          "sideOfStreet": "R", 
          "street": "", 
          "type": "s", 
          "unknownInput": ""
        }
      ], 
      "providedLocation": {
        "city": " ", 
        "postalCode": "", 
        "state": "", 
        "street": "E Blvd"
      }
    }
  ]
}

RIght now i am doing this

data=json.loads(r)
return jsonify(data)

and this prints all the data as shown above. I need to get the latlng array from locations which is in results. I have tried data.get("results").get("locations") and hundreds of combinations like that but i still cant get it to work. I basically need to store the lat and long in a session variable. Any help is appreciated

3
  • You can use data as a dict of dict and list. Commented Aug 11, 2015 at 6:50
  • that is probably above my level of comprehension of python dist and lists, this is my first time doing python. what would it be in terms of a c++ or c approach? thanks! Commented Aug 11, 2015 at 6:52
  • follow this python types Commented Aug 11, 2015 at 6:54

3 Answers 3

3

Assuming you just have one location as in your example:

from __future__ import print_function

import json

r = ...
data = json.loads(r)

latlng = data['results'][0]['locations'][0]['latLng']
latitude = latlng['lat']
longitude = latlng['lng']

print(latitude, longitude)  # 33.663512 -111.958849
Sign up to request clarification or add additional context in comments.

9 Comments

this makes sense but when i try it says TypeError: list indices must be integers, not str Trying to remedy this
@user4992422, ah, I don't think you included all of the output :). Even with the output you did include, I made a small error. Fix your output and I'll fix the code. EDIT: Never mind, I found the error. Editing the answer now.
haha so syntax errors now but i get the error ValueError: View function did not return a response Any clue?
@user4992422, that sounds like something else, not related to this; something to do with Flask. You should ask a separate question for that :).
@user4992422, no problem :). Can you accept this then, so the question will be marked as answered?
|
2

data.get("results") will return a list type object. As list object does not have get attribute, you can not do data.get("results").get("locations")

According to the json you provided, you can do like this:

data.get('results')[0].get('locations') # also a list

This will give you the array. Now you can get the lat and lng like this:

data.get('results')[0].get('locations')[0].get('latLng').get('lat') # lat
data.get('results')[0].get('locations')[0].get('latLng').get('lng') # lng

Comments

0

I summarize my comments as follows:

You can use data as a dict of dict and list.

A quick ref to dict and list:

A dictionary’s keys are almost arbitrary values.

get(key[, default])

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

official docs about stdtypes

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.