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

时间:2014-12-12 07:40:27

标签: python json

我正在使用Python 3从http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson访问实时JSON Feed。这是代码:

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()

我得到以下输出:

Traceback (most recent call last):

  File "<string>", line 420, in run_nodebug
  File "C:\Users\modar\Desktop\jsondata_finished.py", line 56, in <module>
  File "C:\Users\modar\Desktop\jsondata_finished.py", line 50, in main
    else:
  File "C:\Users\modar\jsondata_finished.py", line 13, in printResults
    if "title" in theJSON["metadata"]:
  File "C:\Python33\lib\json\__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "C:\Python33\lib\json\decoder.py", line 352, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: can't use a string pattern on a bytes-like object

我该如何解决这个问题?关于出了什么问题的解释也会很棒。提前致谢。

1 个答案:

答案 0 :(得分:0)

使用请求库,链接到我上面的评论中,您的代码变为:

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

我希望它有所帮助......