2017-04-18 69 views
0

所有,蟒蛇引用JSON數組

我有一個腳本我建立找出所有打開的引入請求,並比較SHA散列,但我似乎無法找到他們....

for repo in g.get_user().get_repos(): 
print (repo.full_name) 
json_pulls = requests.get('https://api.github.com/repos/' + repo.full_name + '/pulls?state=open+updated=<' + str(cutoff_date.date())+ '&sort=created&order=asc') 
if (json_pulls.ok): 
    for item in json_pulls.json(): 
     for c in item.items(): 
      #print(c["0"]["title"]) 
      #print (json.dumps(state)) 
      print(c) 

代碼循環通過現有的回購協議,並列出了引入請求和我得到的輸出:

output

但是,我不能爲我的生活弄清楚如何COLLEC牛逼的各個字段...

我嘗試使用引用:

  1. print(c['title']) - 沒有定義的錯誤
  2. print(c['0']['title']) -a管狀錯誤

我所尋找的是一個每個請求的簡單列表...

title 
id 
state 
base/sha 
head/sha 

Can有人請指出我在Python腳本中引用json項目時做錯了什麼,因爲它讓我發瘋。

完整的代碼是你的課程幫助...:

# py -m pip install <module> to install the imported modules below. 
# 
# 
# Import stuff 
from github import Github 
from datetime import datetime, timedelta 
import requests 
import json 
import simplejson 
# 
# 
#declare stuff 
# set the past days to search in the range 
PAST = 5 

# get the cut off date for the repos 10 days ago 
cutoff_date = datetime.now() - timedelta(days=PAST) 
#print (cutoff_date.date()) 

# Repo oauth key for my repo 
OAUTH_KEY = "(get from github personal keys)" 

# set base URL for API query 
BASE_URL = 'https://api.github.com/repos/' 

# 
# 
# BEGIN STUFF 

# First create a Github instance: 
g = Github(login_or_token=OAUTH_KEY, per_page=100) 

# get all repositories for my account that are open and updated in the last 
no. of days.... 
for repo in g.get_user().get_repos(): 
print (repo.full_name) 
json_pulls = requests.get('https://api.github.com/repos/' + repo.full_name 
+ '/pulls?state=open+updated=<' + str(cutoff_date.date())+ 
'&sort=created&order=asc') 
if (json_pulls.ok): 
    for item in json_pulls.json(): 
     print(item['title'], item['id'], item['state'], item['base']['sha'], 
    item['head']['sha']) 

回購網站是一個簡單的網站,有兩個回購和1個或2引入請求進行對戰。

腳本的想法,當它完成後,它循環遍歷所有回購站,查找比x天更早並且打開的拉請求,找到分支的sha(和sha爲主分支,跳過.....)去除未掌握分支機構分支機構,從而消除舊的代碼和拉的請求,以保持整潔回購....

+0

你能發佈前的for循環的(參閱https://stackoverflow.com/help/mcve)的邏輯,這樣一個可以只複製粘貼文檔片斷並對其進行測試? –

+0

轉儲屏幕截圖。給我們一個可測試的幾行例子輸入。 – tdelaney

+0

它只是'item [「title」]'等等...... – tdelaney

回答

2

json_pulls.json()返回字典列表,所以你可以這樣做:

for item in json_pulls.json(): 
    print (item['title'], item['id'], item['state'], item['base']['sha'], item['head']['sha']) 

有沒有需要遍歷item.items()

+0

@tdelaney我檢查了github文檔,它返回一個JSON對象,應該將其轉換爲Python字典。 – Barmar

+0

哎呀,錯過了一個級別。 – Barmar

+0

是的....就是這樣..這對我來說很好..感謝您的幫助! –

0
for key, value in item.items(): 
    if (key == 'title'): 
     print(value) 
     #Do stuff with the title here 

補充:Json的應該返回一個字典,和dictionary.items()調用時python中for命令將默認搜索一個key->val對。

+1

這是一個昂貴的方式來執行'if'title'項目:' – tdelaney