如何从JSON检索数据

萨马尔·普拉塔普·辛格(Samar Pratap Singh)

我从新闻API检索了JSON格式的数据集。我想从JSON数据中提取新闻描述。

这是我的代码:

import requests
import json
url = ('http://newsapi.org/v2/top-headlines?'
       'country=us&'
       'apiKey=608bf565c67f4d99994c08d74db82f54')
response = requests.get(url)
di=response.json()
di = json.dumps(di)
for di['articles'] in di:
  print(article['title']) 

数据集看起来像这样:

{'status': 'ok', 
 'totalResults': 38, 
 'articles': [
              {'source': 
                {'id': 'the-washington-post', 
                 'name': 'The Washington Post'}, 
               'author': 'Derek Hawkins, Marisa Iati', 
               'title': 'Coronavirus updates: Texas, Florida and Arizona officials say early reopenings fueled an explosion of cases - The Washington Post', 
               'description': 'Local officials in states with surging coronavirus cases issued dire warnings Sunday about the spread of infections, saying the virus was rapidly outpacing containment efforts.', 
               'url': 'https://www.washingtonpost.com/nation/2020/07/05/coronavirus-update-us/', 
               'urlToImage': 'https://www.washingtonpost.com/wp-apps/imrs.php?src=https://arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/K3UMAKF6OMI6VF6BNTYRN77CNQ.jpg&w=1440', 
               'publishedAt': '2020-07-05T18:32:44Z', 
               'content': 'Here are some significant developments:\r\n<ul><li>The rolling seven-day average for daily new cases in the United States reached a record high for the 27th day in a row, climbing to 48,606 on Sunday, … [+5333 chars]'}])

请用这个指导我!

阿萨德·阿里

您的代码中需要进行一些更正..下面的代码应该可以正常工作,并且我已经删除了API KEY以确保在测试前添加一个

import requests
import json
url = ('http://newsapi.org/v2/top-headlines?'
       'country=us&'
       'apiKey=<API KEY>')
di=response.json()
#You don't need to dump json that is already in json format
#di = json.dumps(di)
#your loop is not correctly defined, below is correct way to do it 
for article in di['articles']:
  print(article['title']) 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章