import requests
import json
import csv
# These our are demo API keys, you can use them!
#location = ""
api_key = 'simplyrets'
api_secret = 'simplyrets'
#api_url = 'https://api.simplyrets.com/properties?q=%s&limit=1' % (location)
api_url = 'https://api.simplyrets.com/properties'
response = requests.get(api_url, auth=(api_key, api_secret))
response.raise_for_status()
houseData = json.loads(response.text)
#different parameters we need to know
p = houseData['property']
roof = p["roof"]
cooling = p["cooling"]
style = p["style"]
area = p["area"]
bathsFull = p["bathsFull"]
bathsHalf = p["bathsHalf"]
这是我正在使用的代码片段,尝试从API提供的JSON中获取信息,并将它们放入可以实际使用的变量中。在
我以为当你用json.loads()
加载它时,它会变成一个字典。在
但它告诉我我不能做p = houseData['property']
,因为“list indices must be integers, not str
”。在
我错了,houseData应该是字典吗?
来自https://docs.python.org/2/library/json.html:
如果JSON从最外层的数组开始,它将是一个数组。如果您的JSON最外层是一个关联数组,那么请发布您的JSON,我们可以进一步研究它。在
返回了数百个属性,它们都在一个列表中。在
您需要指定所需的属性,因此对于第一个属性:
问题是
json.loads()
不一定返回字典。如果JSON的外部容器是一个列表,那么json.loads()
将返回一个列表,其中的元素可以是列表或字典。尝试遍历json.loads()
返回的列表。您要查找的字典可能只是json.loads()[0]
或其他元素。在相关问题 更多 >
编程相关推荐