从json获取信息并在函数中使用它

时间:2013-11-22 21:42:33

标签: python json

我是Python的初学者。我遇到问题的是在搜索歌曲并使用该网址在webbrowser.open_new_tab()中播放后从​​我的数组中选择网址。 py文件是:

import json
import Link_Class
import Music_Database
from pprint import pprint
m = Link_Class.MusicLink()
import webbrowser

search = raw_input("Find this Song: ")
results= m.searchSong(search)
pprint(results)

我的json文件是:

{"LinkCollection":

[{"title":"I Will Always Love You" , 
"artist":"Whitney Houston" ,
"link":"http://www.youtube.com/watch?v=3JWTaaS7LdU", 
"id":1},

{"title":"Killing Me Softly" , 
"artist":"Roberta Flack" ,
"link":"http://www.youtube.com/watch?v=LQ2t5e7stVM", 
"id":2}
]}

还有更多,但为了简单起见,我没有在这里写下所有数据。

2 个答案:

答案 0 :(得分:1)

使用json.load可以非常简单地完成:

with open('your_file.json', 'r') as out:
    data = json.load(out)

# then fetch you data

for song in data['LinkCollection']:
    if song['title'] == search:
        webbrowser.open_new_tab(song['link'])
        break

答案 1 :(得分:0)

你只是想打开第一个结果吗?

link = results['LinkCollection'][0]['link']
webbrowser.open_new_tab(link)