我有这个:
import pycurl
import pprint
import json
c = pycurl.Curl()
c.setopt(c.URL, 'https://mydomainname.com')
c.perform()
上面的代码返回如下字典:
{"name":"steve", "lastvisit":"10-02-2012", "age":12}
我想循环浏览该词典并获得年龄:
age : 12
我试过了:
diction = {}
diction = c.perform()
pprint.pprint(diction["age"])
没有数据返回,我收到此错误:
TypeError: 'NoneType' object is unsubscriptable
答案 0 :(得分:15)
c.perform()
不返回任何内容,您需要配置类似文件的对象来捕获值。 BytesIO
object可以执行,然后您可以在通话结束后拨打.getvalue()
:
import pycurl
import pprint
import json
from io import BytesIO
c = pycurl.Curl()
data = BytesIO()
c.setopt(c.URL, 'https://mydomainname.com')
c.setopt(c.WRITEFUNCTION, data.write)
c.perform()
dictionary = json.loads(data.getvalue())
pprint.pprint(dictionary["age"])
如果您未与pycurl
结婚,您可能会发现requests
更容易:
import pprint
import requests
dictionary = requests.get('https://mydomainname.com').json()
pprint.pprint(dictionary["age"])
即使是标准库urllib.request
module也比使用pycurl
更容易:
from urllib.request import urlopen
import pprint
import json
response = urlopen('https://mydomainname.com')
dictionary = json.load(response)
pprint.pprint(dictionary["age"])