gpt4 book ai didi

python - 通过url获取json数据并在python中使用(simplejson)

转载 作者:IT老高 更新时间:2023-10-28 12:47:32 24 4
gpt4 key购买 nike

我想这一定有一个简单的答案,但我很挣扎:我想获取一个 url(输出 json)并在 python 中的可用字典中获取数据。我被困在最后一步了。

>>> import urllib2
>>> import simplejson
>>> req = urllib2.Request("http://vimeo.com/api/v2/video/38356.json", None, {'user-agent':'syncstream/vimeo'})
>>> opener = urllib2.build_opener()
>>> f = opener.open(req)
>>> f.read() # this works
'[{"id":"38356","title":"Forgetfulness - Billy Collins Animated Poetry","description":"US Poet Laureate Billy Collins reads his poem ","url":"http:\\/\\/vimeo.com\\/38356","upload_date":"2006-01-24 15:21:03","thumbnail_small":"http:\\/\\/80.media.vimeo.com\\/d1\\/5\\/47\\/74\\/thumbnail-4774968.jpg","thumbnail_medium":"http:\\/\\/80.media.vimeo.com\\/d1\\/5\\/46\\/85\\/thumbnail-4685118.jpg","thumbnail_large":"http:\\/\\/images.vimeo.com\\/87\\/39\\/873998\\/873998_640x480.jpg","user_name":"smjwt","user_url":"http:\\/\\/vimeo.com\\/smjwt","user_portrait_small":"http:\\/\\/bitcast.vimeo.com\\/vimeo\\/portraits\\/defaults\\/d.30.jpg","user_portrait_medium":"http:\\/\\/bitcast.vimeo.com\\/vimeo\\/portraits\\/defaults\\/d.75.jpg","user_portrait_large":"http:\\/\\/bitcast.vimeo.com\\/vimeo\\/portraits\\/defaults\\/d.100.jpg","user_portrait_huge":"http:\\/\\/bitcast.vimeo.com\\/vimeo\\/portraits\\/defaults\\/d.300.jpg","stats_number_of_likes":"281","stats_number_of_plays":"9173","stats_number_of_comments":23,"duration":"112","width":"320","height":"240","tags":"poetry, poet, online poetry, famous poet, video poetry, modern poetry, famous poem, poetry sites, poetry websites, audio poetry, american poet, animation clips, american poetry, free poetry sites, animation art, free poetry, animated clips, poem, poet laureate"}]'
>>> simplejson.load(f)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python2.5/site-packages/django/utils/simplejson/__init__.py", line 298, in load
parse_constant=parse_constant, **kw)
File "/usr/lib/python2.5/site-packages/django/utils/simplejson/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.5/site-packages/django/utils/simplejson/decoder.py", line 326, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.5/site-packages/django/utils/simplejson/decoder.py", line 344, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

任何想法我哪里出错了?

最佳答案

试试

f = opener.open(req)
simplejson.load(f)

没有先运行 f.read() 。当你运行 f.read() 时,文件句柄的内容会被吞掉,所以当你调用 simplejson.load(f)

时不会留下任何东西

关于python - 通过url获取json数据并在python中使用(simplejson),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1640715/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com