LearningSlowly
LearningSlowly

Reputation: 9451

Parsing JSON error

I am attempting to use a syntax I learned from here on a new application. I am getting an error when I try to parse the results. I believe I am misunderstanding something about this JSON response, as the same syntax works fine on other applications

Typical response is as follows -

outputs =   

[[{u'results': [{u'address_components': [{u'long_name': u'Arumeru',
                                          u'short_name': u'Arumeru',
                                          u'types': [u'administrative_area_level_2',
                                                     u'political']},
                                         {u'long_name': u'Arusha',
                                          u'short_name': u'Arusha',
                                          u'types': [u'administrative_area_level_1',
                                                     u'political']},
                                         {u'long_name': u'Tanzania',
                                          u'short_name': u'TZ',
                                          u'types': [u'country',
                                                     u'political']}],
                 u'formatted_address': u'Arumeru, Tanzania',
                 u'geometry': {u'bounds': {u'northeast': {u'lat': -2.9567556,
                                                          u'lng': 37.0479585},
                                           u'southwest': {u'lat': -3.7703911,
                                                          u'lng': 36.541356}},
                               u'location': {u'lat': -3.2923144,
                                             u'lng': 36.8250274},
                               u'location_type': u'APPROXIMATE',
                               u'viewport': {u'northeast': {u'lat': -2.9567556,
                                                            u'lng': 37.0479585},
                                             u'southwest': {u'lat': -3.7703911,
                                                            u'lng': 36.541356}}},
                 u'types': [u'administrative_area_level_2', u'political']}],
   u'status': u'OK'}]]   


output = open('geocoding_results_Tanzania.csv', 'w+')
writer = csv.DictWriter(output, delimiter=',', fieldnames=['location_lat', 'location_lng'])
writer.writeheader()

pprint([results])

for results in outputs[0]["results"][0]["geometry"]["location"]:
params = {
'location_lat': results['lat'],
'location_lng': results['lng'],
}
writer.writerow(params)

Error -

    location_lat': results['lat'],
TypeError: string indices must be integers

However, when I do as advised by @Padraic

lat = outputs[0]["results"][0]["geometry"]["location"]['lat']
lng = outputs[0]["results"][0]["geometry"]["location"]['lng']
print(lat,lng)

I get, the correct values.

(-3.2923144, 36.8250274)

What am I doing wrong when iterating over the results?

Upvotes: 2

Views: 141

Answers (3)

Padraic Cunningham
Padraic Cunningham

Reputation: 180522

It is results[0][0]["results"], you have a list inside a list.

So:

print(results[0][0]["results"][0]["geometry"])

gest:

{'location_type': 'APPROXIMATE', 'bounds': {'northeast': {'lat': -2.9567556, 'lng': 37.0479585}, 'southwest': {'lat': -3.7703911, 'lng': 36.541356}}, 'location': {'lat': -3.2923144, 'lng': 36.8250274}, 'viewport': {'northeast': {'lat': -2.9567556, 'lng': 37.0479585}, 'southwest': {'lat': -3.7703911, 'lng': 36.541356}}}

You are accessing the wrong way, you can simply:

loc = results[0][0]["results"][0]["geometry"]["location"]

lat, long = loc["lat"], loc["lng"]

print(lat,long)
-3.2923144 36.8250274

The output of results[0][0]["results"][0]["geometry"] is a dict:

{'viewport': {'northeast': {'lng': 37.0479585, 'lat': -2.9567556}, 'southwest': {'lng': 36.541356, 'lat': -3.7703911}}, 'location': {'lng': 36.8250274, 'lat': -3.2923144}, 'location_type': 'APPROXIMATE', 'bounds': {'northeast': {'lng': 37.0479585, 'lat': -2.9567556}, 'southwest': {'lng': 36.541356, 'lat': -3.7703911}}}

When you iterate over results[0][0]["results"][0]["geometry"] you are actually iterating over the keys in the dict so you are then trying to index a string using a string hence the error.

Upvotes: 2

user1213480
user1213480

Reputation: 21

here is the pprint.pprint(result) output:

[[{u'results': [{u'address_components': [{u'long_name': u'Arumeru',
                                          u'short_name': u'Arumeru',
                                          u'types': [u'administrative_area_level_2',
                                                     u'political']},
                                         {u'long_name': u'Arusha',
                                          u'short_name': u'Arusha',
                                          u'types': [u'administrative_area_level_1',
                                                     u'political']},
                                         {u'long_name': u'Tanzania',
                                          u'short_name': u'TZ',
                                          u'types': [u'country',
                                                     u'political']}],
                 u'formatted_address': u'Arumeru, Tanzania',
                 u'geometry': {u'bounds': {u'northeast': {u'lat': -2.9567556,
                                                          u'lng': 37.0479585},
                                           u'southwest': {u'lat': -3.7703911,
                                                          u'lng': 36.541356}},
                               u'location': {u'lat': -3.2923144,
                                             u'lng': 36.8250274},
                               u'location_type': u'APPROXIMATE',
                               u'viewport': {u'northeast': {u'lat': -2.9567556,
                                                            u'lng': 37.0479585},
                                             u'southwest': {u'lat': -3.7703911,
                                                            u'lng': 36.541356}}},
                 u'types': [u'administrative_area_level_2', u'political']}]}]]

the for loop statament 'for geometry in results['results'][0]['geometry']' just gets the below dict's key value

{u'bounds': {u'northeast': {u'lat': -2.9567556, u'lng': 37.0479585},
             u'southwest': {u'lat': -3.7703911, u'lng': 36.541356}
            },
 u'location': {u'lat': -3.2923144, u'lng': 36.8250274},
 u'location_type': u'APPROXIMATE',
 u'viewport': {u'northeast': {u'lat': -2.9567556, u'lng': 37.0479585},
               u'southwest': {u'lat': -3.7703911, u'lng': 36.541356}
              }
}

so the location info should be got as following

geometry = results[0][0]['results'][0]['geometry']
params = {
"location_lat": geometry['location']['lat'],
"location_lng": geometry['location']['lng'],
}

pprint.pprint(params)

Upvotes: -1

jsbueno
jsbueno

Reputation: 110696

So - on the line pasted on the session "Error" above you have a literal Python expresssion - ['results'] on that line is a hard-coded string inside a hardocded list, not a reference to the previous data you have decoded. Your expression takes the [0]'th element from ['results'], which is the string 'results', and tries topick the ['geometry'] element from that.

Try:

location_lat = results[0][0][u'results'][0][u'geometry']

instead

Upvotes: 0

Related Questions