Python:将JSON(由URL返回)转换为列表 [英] Python: Convert JSON (returned by URL) into List
问题描述
我正在请求将youtube搜索字词与jquery自动完成功能配合使用,但是很难将URL响应转换为正确的格式.
I am requesting youtube search terms for use with jquery autocomplete, but am having a hard time converting the URL response into a proper format.
在我的(Django/Python)视图中,我这样做:
In my (Django/Python) view I do:
data2 = urllib2.urlopen('http://suggestqueries.google.com/complete/search?hl=en&ds=yt&client=youtube&hjson=t&jsonp=window.yt.www.suggest.handleResponse&q=jum&cp=3')
(为简单起见,我将搜索字词="jump"硬编码)
(I hardcoded the search term = 'jump' for simplicity)
如果我执行data2.read()
,我得到的是我认为的JSON(将URL复制粘贴到浏览器中也会返回此值.)
If I do data2.read()
I get what I believe is JSON (copy-pasting the url into a browser also returns this.)
window.yt.www.suggest.handleResponse(["jum",[["jumpstyle","","0"],["jump","","1"],["jump around","","2"],["jump on it","","3"],["jumper","","4"],["jump around house of pain","","5"],["jumper third eye blind","","6"],["jumbafund","","7"],["jump then fall taylor swift","","8"],["jumpstyle music","","9"]],"","","","","",{}])
我需要以jquery自动完成功能可以读取的格式返回此内容.我知道如果可以将其放入列表中,例如mylist = ['jumpstyle', 'jump', 'jump around', ...]
I need to return this in a format that jquery autocomplete can read. I know it will work if I can get it into a list, for example, mylist = ['jumpstyle', 'jump', 'jump around', ...]
,然后在将其返回之前将其转换回json:
and then convert it back into json before returning it:
json.dumps(mylist)
(如果我直接按照上面的定义直接定义mylist
,这将起作用.)
(This works if I directly define mylist
directly as written above.)
但是我无法从URL返回的数据获取一个简单列表(然后将其转换回JSON)或某种可以直接返回以供自动完成功能使用的JSON形式.
But I cannot get from the data that is returned by the URL to either a simple list (which I then convert back into JSON) or to some form of JSON that I can return directly to be used by auto complete.
除其他外,我尝试过
j2 = json.loads(data2)
和
j2 = json.loads(data2.read())
希望有人可以提供帮助!
Hope someone can help!
推荐答案
删除&jsonp=window.yt.www.suggest.handleResponse
部分
import json
import urllib2
data = urllib2.urlopen('http://suggestqueries.google.com/complete/search?hl=en&ds=yt&client=youtube&hjson=t&q=jum&cp=3')
j = json.load(data)
k = [i for i, j, k in j[1]]
l = json.dumps(k)
这篇关于Python:将JSON(由URL返回)转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!