如何在python3中输出实时JSON提要?

2024-06-02 15:23:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用python3访问来自http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson的实时JSON提要。代码如下:

try:
    # For Py 3.0+
    from urllib.request import urlopen
except ImportError:
    # For Py 2
    from urllib2 import urlopen

import json

def printResults(data):
  # Use the json module to load the string data into a dictionary
  theJSON = json.loads(data) #pass JSON data into a dictionary

  # now we can access the contents of the JSON like any other Python object
  if "title" in theJSON["metadata"]:
    print (theJSON["metadata"]["title"])

def main():
  # JSON feed of earthquake activity larger than 2.5 in the past 25 hours
  urlData = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson"

  #open url and read contents
  webUrl = urlopen(urlData)
  print (webUrl.getcode())
  if (webUrl.getcode() == 200):
    data = webUrl.read()
    #print results
    printResults(data)

  else:
    print ("Received an error from server " + str(webUrl.getcode()))

if __name__ == "__main__":
  main()

我得到以下输出:

^{pr2}$

我该怎么解决这个问题?对出了什么问题的解释也很好。提前谢谢。在


Tags: thefromimportjsondataifmainfeed
1条回答
网友
1楼 · 发布于 2024-06-02 15:23:22

通过上面我的评论中链接到的请求库,您的代码变成:

quake_data = requests.get('http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson').json()
print(quake_data['metadata']['title'])

我真的希望它能帮助。。。在

相关问题 更多 >