使用标准json和urllib2从网站获取JSON对象

时间:2012-10-01 15:43:01

标签: python json urllib2

我编写了一个代码,使用json和请求从github网站中提取JSON对象:

#!/usr/bin/python

import json
import requests

r = requests.get('https://github.com/timeline.json') #Replace with your website URL

with open("a.txt", "w") as f:
    for item in r.json or []:
        try:
            f.write(item['repository']['name'] + "\n") 
        except KeyError: 
            pass  

这完全没问题。但是,我想使用urllib2和标准json模块做同样的事情。我怎么做?感谢。

1 个答案:

答案 0 :(得分:0)

只需使用urlopen下载数据,然后使用Python的json module进行解析:

import json
import urllib2
r = urllib2.urlopen('https://github.com/timeline.json')

with open("a.txt", "w") as f:
    for item in json.load(r) or []:
        try:
            f.write(item['repository']['name'] + "\n") 
        except KeyError:
            pass 
相关问题