1

I'am trying to get the information from the web api with Python 3 but it gives me an error. That's my code:

import json, urllib.request, requests

def findLocation():
"""returns latlng location value in the form of a list."""

    send_url = 'http://freegeoip.net/json'
    r = requests.get(send_url)
    j = json.loads(r.text)
    lat = j['latitude']
    lon = j['longitude']
    return lat, lon

location = findLocation()
print(findLocation()[0])
print(findLocation()[1])

def readJsonUrl(url):
"""reads the Json returned by the google api and converts it into a format 
that can be used in python."""
    page = urllib.request.urlopen(url)
    data_bytes = page.read()
    data_str = data_bytes.decode("utf-8")
    page.close()

    return data_str
search =readJsonUrl("https://maps.googleapis.com/maps/api/place/textsearch/json?query=indian+restaurantsin+Coventry&location=52.4066,-1.5122&key=AIzaSyCI8n1sI4CDRnsYo3hB_oH1trfxbt2IEaw")

print(search['website'])

Error:

Traceback (most recent call last):
  File "google api.py", line 28, in <module>
    print(search['website'])
TypeError: string indices must be integers

Any help is appreciated.

Eric
  • 2,636
  • 21
  • 25
  • With updated lines now give another error. Traceback (most recent call last): File "google api.py", line 35, in print(search['result']) KeyError: 'result' – Iliyan Mladenov Nov 13 '17 at 21:21

3 Answers3

1

The function you are using readJsonUrl() returns a string not JSON. Therefore, when you try search['website'] it fails because the indices on a string can only be integers. Try parsing the string value to a JSON object. To do this you can try the accepted answer here Convert string to JSON using Python

theBrainyGeek
  • 584
  • 1
  • 6
  • 17
0

data_str is string ( not dict format ) You should convert data_str to dict! just add this line to your code : convert_to_dict = json.loads(data_str). then return convert_to_dict ... and done.

Try this :

import json, urllib.request, requests

def findLocation():

    send_url = 'http://freegeoip.net/json'
    r = requests.get(send_url)
    j = json.loads(r.text)
    lat = j['latitude']
    lon = j['longitude']
    return lat, lon

location = findLocation()
print(findLocation()[0])
print(findLocation()[1])

def readJsonUrl(url):

    page = urllib.request.urlopen(url)
    data_bytes = page.read()
    data_str = data_bytes.decode("utf-8")
    page.close()

    convert_to_dict = json.loads(data_str)  # new line

    return convert_to_dict  # updated


search = readJsonUrl("https://maps.googleapis.com/maps/api/place/textsearch/json?query=indian+restaurantsin+Coventry&location=52.4066,-1.5122&key=AIzaSyCI8n1sI4CDRnsYo3hB_oH1trfxbt2IEaw")
print(search['your_key']) # now you can call your keys
DRPK
  • 2,023
  • 1
  • 14
  • 27
0

The reason for for the TypeError: string indices must be integers is because your readJsonUrl function is returning str object instead of dict object. Using the json.loads function can help you transfer the str object to dict object.

You can try something like the following:

def readJsonUrl(url):
    with (urllib.request.urlopen(url)) as page:
        raw = page.read().decode("utf-8")
    json_data = json.loads(raw)
    return json_data

search =readJsonUrl("https://maps.googleapis.com/maps/api/place/textsearch/json?query=indian+restaurantsin+Coventry&location=52.4066,-1.5122&key=AIzaSyCI8n1sI4CDRnsYo3hB_oH1trfxbt2IEaw")

print(search['results'])

Hope it helps.

Eric
  • 2,636
  • 21
  • 25