2014-03-28 107 views
0

當前我正在嘗試創建一個python腳本,通過請求特殊url並獲取信息來運行我的sickbeard api代碼。它輸出下面的代碼是正確的:搜索sickbeard 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

幾點。首先,該數據的工作,你需要將其轉換爲字典(這是很容易用字典的工作比字符串):

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') 

讓你使用詞典aknowledged這可能是有用的 - http://www.tutorialspoint.com/python/python_dictionary.htm

+0

首先感謝您的幫助的。雖然第10行出現錯誤'show_data'未定義。現在我改變了tv_shows,它運行但沒有再顯示任何東西:( – Datechnoman

+0

也如果我但打印語句下打印tv_shows ['show_name']和說print('它工作')並運行它,它什麼都不顯示再次 – Datechnoman

+0

@Datechnoman是的,錯過了。看到編輯答案。 –