nytimes api错误:必须是int而不是str

时间:2015-04-26 13:45:38

标签: python json

嘿那些伙计我试图从nytimes api收集信息但是我收到了这个错误:http://dpaste.com/3YKD9Z9

这是我正在尝试使用的方法的代码:

def fetcharticle(apikey, url):
    '''returns the JSON data of the most
    popular articles by view from the past 24 hours.'''
    parameters = {'api-key' : apikey}
    req = requests.get(url, params=parameters)
    data = json.loads(req.content)
    parsedData = []
    newsData = {}
    for datum in data:
        newsData['title'] = data['results']['title']
        newsData['abstract'] = data['results']['abstract']
        newsData['section'] = data['results']['section']
        newsData['byline'] = data['results']['byline']
        newsData['views'] = data['results']['views']
    parsedData.append(newsData)
    return parsedData

这是网址:http://api.nytimes.com/svc/mostpopular/v2/mostviewed/all-sections/1.json

1 个答案:

答案 0 :(得分:5)

看起来function saveFile(str, part) { var textFileAsBlob = new Blob([str], {type:"text/plain"}); var fileNameToSaveAs = "Parsed audio - part "+part; var downloadLink = document.createElement("a"); downloadLink.download = fileNameToSaveAs; downloadLink.innerHTML = "Download File"; if (window.URL != null) { // Chrome allows the link to be clicked // without actually adding it to the DOM. downloadLink.href = window.URL.createObjectURL(textFileAsBlob); } downloadLink.click(); } 是一个列表 - 索引到带有字符串的列表会引发该错误。

results

这可能意味着您应该遍历结果列表。更一般地说,您的代码没有意义。你想在循环中声明a = [] a["Hi!"] # Bam. Type error, trying to index into a list with a str. dict,这样你就不会经常覆盖它。我认为这就是你要做的事情:

newsData

使用for datum in data['results']: newsdata = {} newsData['title'] = datum['title'] newsData['abstract'] = datum['abstract'] newsData['section'] = datum['section'] newsData['byline'] = datum['byline'] newsData['views'] = datum['views'] parsedData.append(newsData) 文字和正确的pep8格式编写更好:

dict

当然,问题是你为什么要复制for datum in data['results']: news_data = {"title": datum["title"], "abstract": datum["abstract"], "section": datum["section"], "byline": datum["byline"], "views": datum["views"]} parsed_data.append(news_data) 中的这么多字段 - 也许你可以只使用datum字典本身,而扩展名{{1}在datum键:

list