搜索sickbeard api输出并仅打印关键字行

时间:2014-03-28 11:06:21

标签: python list for-loop for-in-loop

目前我正在尝试创建一个python脚本,它将通过请求特殊URL并获取信息来运行我的病态api代码。它输出的代码是正确的:

{
    "data": {
        "missed": [
            {
                "airdate": "2014-03-27", 
                "airs": "Friday 02:05", 
                "ep_name": "Episode 24", 
                "ep_plot": "", 
                "episode": 24, 
                "network": "MBS", 
                "paused": 0, 
                "quality": "SD", 
                "season": 1, 
                "show_name": "Kill la Kill", 
                "show_status": "Continuing", 
                "tvdbid": 272074, 
                "weekday": 4
            }, 
            {
                "airdate": "2014-03-27", 
                "airs": "Thursday 10:00 PM", 
                "ep_name": "Tyga", 
                "ep_plot": "", 
                "episode": 18, 
                "network": "MTV", 
                "paused": 0, 
                "quality": "SD", 
                "season": 4, 
                "show_name": "Ridiculousness", 
                "show_status": "Continuing", 
                "tvdbid": 250793, 
                "weekday": 4
            }, 
            {
                "airdate": "2014-03-27", 
                "airs": "Thursday 10:00 PM", 
                "ep_name": "Guy Fieri", 
                "ep_plot": "", 
                "episode": 19, 
                "network": "MTV", 
                "paused": 0, 
                "quality": "SD", 
                "season": 4, 
                "show_name": "Ridiculousness", 
                "show_status": "Continuing", 
                "tvdbid": 250793, 
                "weekday": 4
            }
        ]
    }, 
    "message": "", 
    "result": "success"
}

现在我希望它只显示带有关键字“show_name”的行。例如,我希望它只显示“杀死杀人”,荒谬和荒谬。我将使用这个,所以如果我说命令“今天的节目是什么”它将运行python脚本并输出今天的节目。每当我运行代码时它就会运行并且什么都不显示。

from urllib2 import Request, urlopen, URLError

request = Request('http://192.168.1.***:8081/api/*****/?cmd=future&sort=date&type=missed')

try:
    response = urlopen(request)
    tv_shows = response.read()
    for single_line in tv_shows:
        if 'show_name' in single_line:
            print single_line

except URLError, e:
    print ('Error') 

我是python编程的新手,所以任何帮助都非常感谢。

1 个答案:

答案 0 :(得分:1)

几点。首先,要处理这些数据,您需要将其转换为字典(使用字典比使用字符串更容易):

import json

...

tv_shows = json.loads(response.read())

其次,要访问您感兴趣的列表,请使用tv_shows['data']['missed']

因此,您的代码可能如下所示:

import json
from urllib2 import Request, urlopen, URLError

request = Request('http://192.168.1.***:8081/api/*****/?cmd=future&sort=date&type=missed')

try:
    response = urlopen(request)
    tv_shows = json.loads(response.read())
    for show_data in tv_shows['data']['missed']:
        if 'show_name' in show_data:
            print show_data['show_name']

except URLError, e:
    print ('Error')

这对于让您熟悉词典 - http://www.tutorialspoint.com/python/python_dictionary.htm

非常有用