python - 在python中从JSON中检索数据,如果对象名称匹配,则存储该对象的 key

标签 python json rest

我正在服务器上进行 REST 调用。第一个 REST 调用获取所有项目,并将项目的 ID 存储在数组中。 下面是 JSON。 例如它会返回类似这样的内容:

[
    {
        "expand": "description,lead,url,projectKeys",
        "self": "http://localhost:8080/rest/api/2/project/10101",
        "id": "10101",
        "key": "GR1",
        "name": "Group1Project",
        "avatarUrls": {
            "48x48": "http://localhost:8080/secure/projectavatar?avatarId=10324",
            "24x24": "http://localhost:8080/secure/projectavatar?size=small&avatarId=10324",
            "16x16": "http://localhost:8080/secure/projectavatar?size=xsmall&avatarId=10324",
            "32x32": "http://localhost:8080/secure/projectavatar?size=medium&avatarId=10324"
        },
        "projectTypeKey": "software"
    }
]

然后我循环遍历该数组并对每个项目 id (10101) 进行另一个 REST 调用。 这给了我反对该项目的组/用户。 例如:

{
    "self": "http://localhost:8080/rest/api/2/project/10000/role/10100",
    "name": "Developers",
    "id": 10100,
    "actors": [
        {
            "id": 10207,
            "displayName": "group2",
            "type": "atlassian-group-role-actor",
            "name": "group2",
            "avatarUrl": "http://localhost:8080/secure/useravatar?size=xsmall&avatarId=10123"
        }
    ]
}

我想获取 name == group2 的所有项目 ID。

以下是我的 Python 代码,但它不起作用。

import requests

ids = []

response = requests.get('http://localhost:8080/rest/api/2/project',
                        auth=('*', '*'))
data = response.json()

for line in data:
    ids.append(line["id"])

print(ids)  


# Check if group exists in Project roles.
# If it does, then save the project name in the list of arrays.

projectNames = []

for id in ids:
    url = 'http://localhost:8080/rest/api/2/project/'+id+'/role/10100'
    response = requests.get(url,
                            auth = ('*', '*'))

    data = response.json()

    if data.displayName == 'group2':
        projectNames.append(["id"])

您能帮我解决一下这个问题吗? 谢谢。

最佳答案

塔亚布, 你需要这样做。它会起作用的。

for actor in data['actors']:
    if actor['displayName']=='group2':
        projectNames.append(id)

关于python - 在python中从JSON中检索数据,如果对象名称匹配,则存储该对象的 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43977236/

相关文章:

python - 指数拟合与对数线性拟合之间的差异

javascript - 动态创建 html div jinja2 和 ajax

javascript - Angular -Js $http.post 在 Django 中不起作用

html - AJAX 响应 : Data (JSON, XML)或 HTML 片段?

java - Jersey rest 服务器 - 将列表的不同结构返回为 json

rest - 在使用 Auth0 的 golang 服务器中找出当前用户名

python - Flask替代品实现真正的多线程?

web-services - RESTful用户身份验证服务

rest - 如何使用 H2O REST API 创建 H2OFrame

javascript - 尝试在shopify中创建幻灯片放映变体