在Python中从JSON文件中选择值

5
我正在使用以下Python代码获取JIRA数据,如何存储多个关键字的响应(示例中只显示一个KEY,但通常我会得到很多数据),并打印与 total、key、customfield_12830和summary 相对应的值。
    import requests
    import json
    import logging
    import datetime
    import base64
    import urllib
    serverURL = 'https://jira-stability-tools.company.com/jira'
    user = 'username'
    password = 'password'
    query = 'project = PROJECTNAME AND "Build Info" ~ BUILDNAME  AND assignee=ASSIGNEENAME'
    jql = '/rest/api/2/search?jql=%s' % urllib.quote(query)
    response = requests.get(serverURL + jql,verify=False,auth=(user, password))
    print response.json()

response.json() 的输出如下:

http://pastebin.com/h8R4QMgB


请查看相关问题:https://dev59.com/Nl4c5IYBdhLWcg3wT41O - WannaBeCoder
Charles - 有没有一个外部链接,我可以将我的示例输出粘贴在这里并分享给大家? - user5007666
Charles - http://pastebin.com/h8R4QMgB 是包含4个项目的链接,很抱歉数据量太大需要筛选。 - user5007666
1
@PythonProg,...你可能会注意到,pastebin.com是我要求你不要使用的那个pastebin -- 它充满了广告,对于没有使用AdBlock或类似工具的人来说。 - Charles Duffy
@ Charles Duffy - 为什么不指向一个你推荐的 pastebin? - user5007666
显示剩余3条评论
1个回答

1

从您粘贴到pastebin的链接和我看到的json中,它是一个包含key, fields(其中包含自定义字段), self, id, expandissues列表。

您可以简单地遍历此响应并提取所需键的值。您可以像这样进行操作。

data = response.json()
issues = data.get('issues', list())

x = list()

for issue in issues:
    temp = {
        'key': issue['key'],
        'customfield': issue['fields']['customfield_12830'],
        'total': issue['fields']['progress']['total']
    }
    x.append(temp)
print(x)

x 是包含你提到的字段数据的字典列表。如果我有什么地方不清楚或者我给出的不是你要找的,请告诉我。

PS: 建议始终使用 dict.get('keyname', None) 获取值,因为如果找不到键,你可以始终放置一个默认值。对于这个解决方案,我没有这样做,因为我只想提供方法。

更新: 在评论中,你(OP)提到它会产生 attributerror。尝试这段代码。

data = response.json()
issues = data.get('issues', list())

x = list()

for issue in issues:
    temp = dict()
    key = issue.get('key', None)
    if key:
       temp['key'] = key 

    fields = issue.get('fields', None)
    if fields:
        customfield = fields.get('customfield_12830', None)
        temp['customfield'] = customfield

        progress = fields.get('progress', None)
        if progress:
            total = progress.get('total', None)
            temp['total'] = total

    x.append(temp)
print(x)

这就是我提到使用 dict.get('keyname', None) 的原因,以确保您尝试访问的键确实存在。对于您来说,当您尝试访问值为字典的 'fields' 或者可能是字典的 'progress' 时,会引发此错误。为了避免这种情况,请使用 fields = issue.get('fields', None)。然后,如果 fields 存在,则尝试在其中访问您的自定义字段。 - Rajesh Yogeshwar
data = response.json().get('data') 这段代码本身打印出 None,而 data = response.json() 则打印出正确的数据。那么 get('data') 是做什么的呢? - user5007666
哦,那个,我是出于习惯这么做的,已经更新了答案,请检查一下。 - Rajesh Yogeshwar
1
Rajesh - 你使用了什么工具来解析这个结构吗?你建议初学者如何理解这个结构并自己完成它? - user5007666
1
@PythonProg,...我之前也建议使用pprint作为在Python世界中解密结构的工具。在JSON方面,jq或者只是python -m json.tool通常就足够了。 - Charles Duffy
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接