我正在处理我的第一个使用API的项目,但我无法访问数据。我正在研究一个用这个循环调用其数据的例子:
for item in data['objects']:
print item['name'], item['phone']
这适用于存储为嵌套字典的数据(外部称为对象,内部包含数据)
我遇到的问题是我的数据是使用列表中的dictonaries格式化的
[
{
"key":"2014cama",
"website":"http://www.cvrobotics.org/frc/regional.html",
"official":true,
"end_date":"2014-03-09",
"name":"Central Valley Regional",
"short_name":"Central Valley",
"facebook_eid":null,
"event_district_string":null,
"venue_address":"Madera South High School\n705 W. Pecan Avenue\nMadera, CA 93637\nUSA",
"event_district":0,
"location":"Madera, CA, USA",
"event_code":"cama",
"year":2014,
"webcast":[],
"timezone":"America/Los_Angeles",
"alliances":[],
"event_type_string":"Regional",
"start_date":"2014-03-07",
"event_type":0
},'more data...']
所以打电话,
for item in data['objects']:
print item['name']
无法提取name
中存储的值。
非常感谢任何帮助。
修改:完整的数据集I' m(http://www.thebluealliance.com/api/v2/team/frc254/2014/events?X-TBA-App-Id=Peter_Hartnett:Scouting:v1)
我正在运行的代码:
import json,urllib2, TBA
team ='frc254'
year = '2014'
Url = 'http://www.thebluealliance.com/api/v2/team/'+team+'/'+year+'/events?X- TBA-App-Id=Peter_Hartnett:Scouting:v1'
data = TBA.GetData(Url)
for item in data:
print item['name']
TBA类只导入数据并将其返回。
EDIT2: 这是拉取数据的TBA类,我可以向你保证它与上面链接中的相同
import urllib2,cookielib
content='none'
def GetData(Url):
site= Url
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept': ' 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'}
req = urllib2.Request(site, headers=hdr)
try:
page = urllib2.urlopen(req)
except urllib2.HTTPError, e:
print e.fp.read()
content = page.read()
return content
答案 0 :(得分:1)
如果我理解正确,你的data['objects']
现在是列表中的条目,对吗?
所以只需迭代列表,你的逻辑将保持不变
for item in objects:
print item['name'], item['phone']
正在
objects = [
{
"key":"2014cama",
"website":"http://www.cvrobotics.org/frc/regional.html",
"official":true,
"end_date":"2014-03-09",
"name":"Central Valley Regional",
"short_name":"Central Valley",
"facebook_eid":null,
"event_district_string":null,
"venue_address":"Madera South High School\n705 W. Pecan Avenue\nMadera, CA 93637\nUSA",
"event_district":0,
"location":"Madera, CA, USA",
"event_code":"cama",
"year":2014,
"webcast":[],
"timezone":"America/Los_Angeles",
"alliances":[],
"event_type_string":"Regional",
"start_date":"2014-03-07",
"event_type":0
},'more data...']
我现在得到你的问题。您的对象data
是string
,代表JSONArray
。您应该在迭代之前 加载 ,以便能够将其作为真正的list
使用,如下所示:
data = GetData(Url)
loaded_array = json.loads(data)
for item in loaded_array:
print item['name']