Iliyan Mladenov
Iliyan Mladenov

Reputation: 19

How to load from Json?

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.

Upvotes: 1

Views: 657

Answers (3)

Eric
Eric

Reputation: 2729

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.

Upvotes: 0

DRPK
DRPK

Reputation: 2091

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

Upvotes: 0

theBrainyGeek
theBrainyGeek

Reputation: 584

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

Upvotes: 1

Related Questions