如何从Json加载?

时间:2017-11-13 20:41:41

标签: python-3.x api urllib restful-url

我试图通过Python 3从web api获取信息,但它给了我一个错误。那是我的代码:

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'])

错误:

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

感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

您正在使用的函数readJsonUrl()返回的字符串不是JSON。因此,当您尝试search['website']时,它会失败,因为字符串上的索引只能是整数。 尝试将字符串值解析为JSON对象。为此,您可以在Convert string to JSON using Python

尝试接受的答案

答案 1 :(得分:0)

data_str 是字符串(不是dict格式)您应该将 data_str 转换为dict!只需将此行添加到您的代码中:convert_to_dict = json.loads(data_str)。然后返回convert_to_dict ...并完成。

试试这个:

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

答案 2 :(得分:0)

array_search()的原因是因为您的$key=array_search($yourId,$idsArray);函数正在返回 str 对象而不是 dict 对象。使用json.loads功能可以帮助您将 str 对象转移到 dict 对象。

您可以尝试以下内容:

TypeError: string indices must be integers

希望它有所帮助。