Search code examples
pythonpython-2.7jython

How to create a list from api reponse and remove duplicates


I want to make a list from api json response as shown for each ticket in jira and remove any duplicates

I can get the values for each ticket but not able to make it as list and remove duplicates from it to process

Here is the api json response for each ticket

response = {
    "expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
    "id": "1831845",
    "self": "https://jira.com/login/rest/api/latest/issue/1845",
    "key": "pc-1002",
    "fields": {
                 "customfield_1925": {
                    "self": "https://jira.com/login/rest/api/2/customFieldOption/1056",
                    "value": "windows",
                    "id": "101056"
                }

so i have script like this:

import requests, json

tick = """jira: pc-1002,pc-1003,pc-1005
env"""
ticks = tick.replace(' ','').split(':')[1].split('\n')[0].split(',')
print(ticks)

for i in ticks:
    url = "https://jira.com/login/rest/api/latest/issue/" + str(i)
    print(url)

    response = requests.request("GET", url, verify=False)
    response = json.loads(response.text)
    resp = response['fields']['customfield_1925']['value']   
    print(resp)

so it prints all the values like below : output:

windows1 windows2 windows1

I want the output values to be unique and as it may end up having duplicates.

I wanted output as below

['windows1', 'windows2']


Solution

  • Simply add each response to a list of responses, and use Python's convenient "in" operator to check if each response is already in the list. Something along the lines of:

        allResponses = []
        for i in ticks:
            url = "https://jira.com/login/rest/api/latest/issue/" + str(i)
            print(url)
    
            response = requests.request("GET", url, verify=False)
            response = json.loads(response.text)
            resp = response['fields']['customfield_1925']['value']
            if resp not in allResponses:   
                print(resp)
                allResponses.append(resp)