首页 > 解决方案 > 追加到列表每次都会换行?

问题描述

我试图让在我的字典中的 JSON 输出中找到的每一个出现都附加到一个列表中,但是每次它找到另一个出现时,它都会创建一个新列表并添加新列表。我相信这可能与我的 for 循环有关,但我不确定。

我的代码:

def get_all_asset_groups():

    path1 = "/api/3/asset_groups/?size=300"
    url5 = server + path1
    response = requests.request("GET", url5, headers=headers, verify=False)
    data = response.json()
    x = (json.dumps(data, indent=2, sort_keys=True))

    server_owners_dict=dict()
    owners= []

    #populating the dictionary with the server owners
    for i in data['resources']:
            if 'id' in i and 'name' in i:
                b = i['name'], i['id']
                k = str(b)
                if  re.findall("'Server-Ownership-\w+', \w+", k):
                    matchedOwners = re.findall("'Server-Ownership-\w+', \w+", k)[0]
                    j = str(matchedOwners).strip().split() 
                    server_owners_dict[j[0].replace('Server-Ownership-','')]=j[1]               

    with open(PATH, mode='w') as my_csv_file:
        employee_writer = csv.writer(my_csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        employee_writer.writerow(['Server Name','Criticals'])
        for owner in server_owners_dict:
            url = server + "/api/3/asset_groups/" + str(server_owners_dict[owner]) + "/assets"
            response = requests.request("GET", url, headers=headers, verify=False, params = {owner:server_owners_dict[owner]})
            data = response.json()
            for i in data['resources']:
                url = server+ "/api/3/assets/" + str(i)
                response = requests.request("GET", url, headers=headers, verify=False)
                data = response.json()
                if data['vulnerabilities']['critical'] > 0:
                    d = owner                    
                    owners.append(owner)
                    print(owners)

输出:

["'Bob',"]
["'Bob',", "'Bob',"]
["'Bob',", "'Bob',", "'Bob',"]

我希望它是什么:

["'Bob',","'Bob',","'Bob',"]

另外,有什么办法可以摆脱这些多余的字符:

["Bob", "Bob", "Bob"]

标签: pythonlistfor-loopappend

解决方案


推荐阅读