python引用json数组

时间:2017-04-18 16:11:16

标签: python json reference

所有,

我正在构建一个脚本来查找所有打开的拉取请求并比较sha hash,但我似乎无法找到它们....

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)

代码循环通过现有的repos并列出pull请求,我得到输出:

output

但是,我不能为我的生活找出如何收集个别领域......

我尝试使用引用:

  1. print(c['title']) - 未定义错误
  2. print(c['0']['title']) -a管道错误
  3. 我正在寻找的是每个请求的简单列表....

    title
    id
    state
    base / sha
    head / sha 
    

    有人可以在我的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,到跳过.....)删除不是主分支的分支,从而删除旧代码并拉取请求以保持repos整洁....

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

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

要添加:Json应该作为dict返回,并且python中的for命令将在key->val上调用时默认搜索dictionary.items()对。